@nativestudio/cli 0.3.0-rc.6 → 0.3.0-rc.7
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/LICENSE +201 -21
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-CA54SKBO.js → chunk-6SYHA2B4.js} +1 -1
- package/dist/_chunks/{chunk-GJ7BZJLW.js → chunk-A7EUJNCL.js} +1 -1
- package/dist/_chunks/chunk-AJ7S73M4.js +1 -0
- package/dist/_chunks/chunk-DRHPICBU.js +1 -0
- package/dist/_chunks/chunk-FCHO4AVP.js +1 -0
- package/dist/_chunks/chunk-JH5QP6PC.js +1 -0
- package/dist/_chunks/chunk-LF442QV6.js +1 -0
- package/dist/_chunks/chunk-LUBHPAPW.js +1 -0
- package/dist/_chunks/chunk-OZ5KZSTM.js +1 -0
- package/dist/_chunks/chunk-RJ4QQF7E.js +1 -0
- package/dist/_chunks/chunk-RT5PFKYS.js +1 -0
- package/dist/_chunks/chunk-SIJPJIBO.js +1 -0
- package/dist/_chunks/{chunk-KNFUMWDY.js → chunk-TCZJLYSR.js} +1 -1
- package/dist/_chunks/chunk-TTFDNLQE.js +1 -0
- package/dist/_chunks/chunk-URKX77KR.js +1 -0
- package/dist/_chunks/chunk-XRYARPEL.js +1 -0
- package/dist/_chunks/device-management-4XIITODX.js +1 -0
- package/dist/_chunks/device-preflight-SDA7Q3LH.js +1 -0
- package/dist/_chunks/devices-inventory-RVHGI2YW.js +1 -0
- package/dist/_chunks/devices-main-WOILNAGY.js +1 -0
- package/dist/_chunks/http-profile-XCHTSJV4.js +1 -0
- package/dist/_chunks/library-main-ZQKJQNHE.js +1 -0
- package/dist/_chunks/local-main-DX47PKHX.js +1 -0
- package/dist/_chunks/local-mcp-HMS5ODZN.js +1 -0
- package/dist/_chunks/main-HQGVZ2O2.js +2 -0
- package/dist/_chunks/mcp-6Q4ALHN6.js +1 -0
- package/dist/_chunks/project-connect-U2IHGC5W.js +1 -0
- package/dist/_chunks/render-main-A2AABFAG.js +1 -0
- package/dist/_chunks/source-import-5N4KZMTC.js +1 -0
- package/dist/_chunks/src-NIMTPR5W.js +1 -0
- package/dist/_chunks/{stdio-main-4Z2JVCMO.js → stdio-main-JJCNIY4H.js} +1 -1
- package/dist/_chunks/workspace-main-ZIZO4WRI.js +1 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +1077 -564
- package/dist/_types/cli/local/desktop-device-contract.d.ts +170 -556
- package/dist/_types/cli/local/desktop-device-owner.d.ts +16 -50
- package/dist/_types/cli/local/desktop-device-state.d.ts +198 -31
- package/dist/_types/cli/local/desktop-library.d.ts +853 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +220 -39
- package/dist/_types/cli/local/ledger.d.ts +2 -0
- package/dist/_types/cli/local/manager.d.ts +352 -22
- package/dist/_types/cli/local/mcp-tools.d.ts +218 -39
- package/dist/_types/cli/local/project-render-tools.d.ts +8742 -77
- package/dist/_types/cli/local-management.d.ts +2 -1
- package/dist/_types/contracts/artifact-discovery.d.ts +76 -4
- package/dist/_types/contracts/audio.d.ts +4 -0
- package/dist/_types/contracts/composition-authoring.d.ts +8 -8
- package/dist/_types/contracts/composition-frame-render.d.ts +4 -4
- package/dist/_types/contracts/composition-render-base.d.ts +5 -4
- package/dist/_types/contracts/composition-render.d.ts +8 -8
- package/dist/_types/contracts/composition-repair.d.ts +10 -10
- package/dist/_types/contracts/composition-source-review.d.ts +12 -12
- package/dist/_types/contracts/delivery-manifest.d.ts +25 -11765
- package/dist/_types/contracts/delivery-operations.d.ts +51 -3921
- package/dist/_types/contracts/delivery-summary.d.ts +2 -2
- package/dist/_types/contracts/delivery-validation.d.ts +23 -0
- package/dist/_types/contracts/device-render.d.ts +67 -0
- package/dist/_types/contracts/editor-intelligence.d.ts +114 -2491
- package/dist/_types/contracts/exploration-recommendation.d.ts +263 -11655
- package/dist/_types/contracts/external-agent-access.d.ts +9 -3
- package/dist/_types/contracts/final-ready.d.ts +22 -22
- package/dist/_types/contracts/final-render.d.ts +1569 -6949
- package/dist/_types/contracts/human-identity.d.ts +13 -0
- package/dist/_types/contracts/index.d.ts +3 -0
- package/dist/_types/contracts/interface/media-output.d.ts +28 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +15 -193
- package/dist/_types/contracts/keyframe-generation.d.ts +29 -0
- package/dist/_types/contracts/local-execution/agent-evidence.d.ts +2 -2
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +2 -2
- package/dist/_types/contracts/local-execution/agent-review.d.ts +30 -285
- package/dist/_types/contracts/local-execution/common.d.ts +12 -11
- package/dist/_types/contracts/local-execution/completion.d.ts +41 -45
- package/dist/_types/contracts/local-execution/device-authority.d.ts +31 -0
- package/dist/_types/contracts/local-execution/device-inventory.d.ts +76 -0
- package/dist/_types/contracts/local-execution/device-workspace.d.ts +11 -0
- package/dist/_types/contracts/local-execution/device.d.ts +19 -59
- package/dist/_types/contracts/local-execution/external-generation.d.ts +199 -0
- package/dist/_types/contracts/local-execution/index.d.ts +19 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1517 -711
- package/dist/_types/contracts/local-execution/library-command.d.ts +620 -0
- package/dist/_types/contracts/local-execution/library-result.d.ts +408 -0
- package/dist/_types/contracts/local-execution/library.d.ts +873 -0
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +21 -5
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +161 -44
- package/dist/_types/contracts/local-execution/management.d.ts +214 -208
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +5 -1
- package/dist/_types/contracts/local-execution/media-validation-request.d.ts +232 -0
- package/dist/_types/contracts/local-execution/media-validation.d.ts +262 -0
- package/dist/_types/contracts/local-execution/object-transfer.d.ts +155 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +120 -10988
- package/dist/_types/contracts/local-execution/processor-capability.d.ts +39 -0
- package/dist/_types/contracts/local-execution/processor-direct.d.ts +290 -0
- package/dist/_types/contracts/local-execution/processor-recipes.d.ts +1122 -0
- package/dist/_types/contracts/local-execution/processor.d.ts +6173 -0
- package/dist/_types/contracts/local-execution/project-source-direct.d.ts +201 -0
- package/dist/_types/contracts/local-execution/qwen-tts.d.ts +31 -0
- package/dist/_types/contracts/local-execution/recognition.d.ts +170 -0
- package/dist/_types/contracts/local-execution/speech.d.ts +95 -0
- package/dist/_types/contracts/local-execution/tool-selection.d.ts +45 -5
- package/dist/_types/contracts/local-execution/whisper.d.ts +24 -0
- package/dist/_types/contracts/local-execution/work.d.ts +69 -10741
- package/dist/_types/contracts/local-execution/workspace.d.ts +5 -0
- package/dist/_types/contracts/media-category.d.ts +11 -0
- package/dist/_types/contracts/media-observation.d.ts +929 -8
- package/dist/_types/contracts/observation-profile.d.ts +3 -3
- package/dist/_types/contracts/programmatic-composition.d.ts +24 -24
- package/dist/_types/contracts/programmatic-exploration.d.ts +348 -6009
- package/dist/_types/contracts/provider-catalog.d.ts +3 -3
- package/dist/_types/contracts/provider-models.d.ts +16 -8
- package/dist/_types/contracts/provider.d.ts +66 -1
- package/dist/_types/contracts/reference-preview.d.ts +19 -0
- package/dist/_types/contracts/repair-lifecycle.d.ts +52 -384
- package/dist/_types/contracts/repair-plan.d.ts +16 -98
- package/dist/_types/contracts/repair-strategy.d.ts +162 -4505
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +317 -8163
- package/dist/_types/contracts/review-intelligence.d.ts +450 -11468
- package/dist/_types/contracts/rough-cut-manifest.d.ts +1 -0
- package/dist/_types/contracts/rough-cut-review.d.ts +134 -12566
- package/dist/_types/contracts/rough-cut.d.ts +1076 -5731
- package/dist/_types/contracts/sound-making-plan.d.ts +3 -2
- package/dist/_types/contracts/speech-cost.d.ts +81 -0
- package/dist/_types/contracts/speech.d.ts +149 -0
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +1 -0
- package/dist/_types/contracts/timeline-audio.d.ts +1 -0
- package/dist/_types/contracts/timeline-manifest.d.ts +2 -0
- package/dist/_types/contracts/timeline-source-sound.d.ts +1 -0
- package/dist/_types/contracts/timeline-v2.d.ts +4 -0
- package/dist/_types/contracts/timeline-version-reader.d.ts +10 -0
- package/dist/_types/contracts/timeline-visual-layers.d.ts +4 -0
- package/dist/_types/contracts/timeline.d.ts +50 -4850
- package/dist/_types/contracts/transcription.d.ts +1 -1
- package/dist/_types/contracts/video-generation.d.ts +33 -0
- package/dist/_types/contracts/visual-layer-render.d.ts +37 -6
- package/dist/_types/contracts/visual-sequence.d.ts +22 -0
- package/dist/_types/contracts/workspace.d.ts +22 -0
- package/dist/_types/sdk/errors.d.ts +1 -1
- package/dist/_types/sdk/local-runtime/device-client.d.ts +7 -33
- package/dist/_types/sdk/local-runtime/library.d.ts +268 -0
- package/dist/_types/sdk/local-runtime/workspace.d.ts +9 -4
- package/dist/_types/sdk/local-runtime-client.d.ts +477 -32
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/package.json +2 -8
- package/README.md +0 -119
- package/dist/_chunks/chunk-D533YC7J.js +0 -1
- package/dist/_chunks/chunk-HKD6F6M6.js +0 -1
- package/dist/_chunks/chunk-INLSOHAK.js +0 -1
- package/dist/_chunks/chunk-N6S6HCWE.js +0 -1
- package/dist/_chunks/chunk-PBEHCYR7.js +0 -1
- package/dist/_chunks/chunk-RVGDXRPK.js +0 -1
- package/dist/_chunks/chunk-YKOJPJZR.js +0 -1
- package/dist/_chunks/local-main-J2G7OU5E.js +0 -1
- package/dist/_chunks/local-mcp-LCHXL2IE.js +0 -1
- package/dist/_chunks/main-PPA76ARV.js +0 -2
- package/dist/_chunks/mcp-P7W623FE.js +0 -1
- package/dist/_chunks/project-connect-7L2HRJUN.js +0 -1
- package/dist/_chunks/render-main-ZW6UJHGN.js +0 -1
- package/dist/_chunks/src-BXLFLNRG.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{directory,entries,fail,privateAccess,read,sha256,write}from"./chunk-KB2GVAN7.js";import{LocalDeviceTransportConfigurationSchema,LocalDeviceViewSchema,LocalFinalRenderAdmissionSchema,LocalManagementCommandSchema,LocalManagementResultSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson}from"./chunk-FCHO4AVP.js";import{z}from"zod";var DesktopDeviceScopeSchema=z.strictObject({origin:z.url().refine(value=>{const u=new URL(value);return u.origin===value&&(u.protocol==="https:"||u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname))}),tenantId:z.uuid(),principalId:z.uuid()});var digest=z.string().regex(/^[a-f0-9]{64}$/);var DesktopDeviceCallSchema=z.discriminatedUnion("action",[z.strictObject({action:z.literal("inspect")}),z.strictObject({action:z.literal("prove")}),z.strictObject({action:z.literal("media-validation-capability")}),z.strictObject({action:z.literal("media-processing-capability")}),z.strictObject({action:z.literal("connect"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest.optional()}),z.strictObject({action:z.literal("remember-enable"),expectedRevision:z.int().nonnegative(),installationFingerprint:digest}),z.strictObject({action:z.literal("connection-recover")}),z.strictObject({action:z.literal("enroll"),label:z.string().trim().min(1).max(120)}),z.strictObject({action:z.literal("revoke")}),z.strictObject({action:z.literal("preview"),input:StartLocalPreviewSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("final"),input:StartLocalFinalRenderSchema.omit({tenantId:true,placement:true,idempotencyKey:true}),mode:z.enum(["local-only","local-preferred"])}),z.strictObject({action:z.literal("dispatch"),fingerprint:digest}),z.strictObject({action:z.literal("record"),fingerprint:digest,result:LocalManagementResultSchema}),z.strictObject({action:z.literal("refused"),fingerprint:digest})]);var DesktopDeviceRequestSchema=z.strictObject({operation:z.literal("device"),scope:DesktopDeviceScopeSchema,call:DesktopDeviceCallSchema});var DesktopDeviceStateSchema=z.strictObject({revision:z.int().nonnegative(),scope:DesktopDeviceScopeSchema,enrollment:LocalManagementCommandSchema.options[0].shape.input.nullable(),device:LocalDeviceViewSchema.nullable(),previews:z.array(z.union([LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema])).max(20),connectorId:z.uuid().nullable(),connection:z.strictObject({phase:z.enum(["CONNECTING","READY","CONNECTED"]),expiresAt:z.iso.datetime(),tenantMediaProcessing:z.literal(true).optional(),processorCapabilities:LocalDeviceTransportConfigurationSchema.shape.processorCapabilities,deviceRevision:z.int().positive(),tenantMediaValidation:z.literal(true).optional()}).nullable().default(null),pending:z.strictObject({command:LocalManagementCommandSchema,fingerprint:digest,phase:z.enum(["PREPARED","SENDING","REFUSED"])}).nullable()});var DesktopDeviceViewSchema=DesktopDeviceStateSchema.omit({scope:true,enrollment:true,connectorId:true,pending:true,device:true}).extend({installation:z.strictObject({version:z.string().min(1).max(100),fingerprint:digest,workProtocol:z.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]).optional()}).nullable().optional(),automaticConnection:z.boolean().optional(),device:z.strictObject({deviceId:z.uuid(),label:z.string().max(120),revision:z.int().positive(),revokedAt:z.iso.datetime().nullable()}).nullable(),pending:z.strictObject({kind:z.enum(["ENROLL","REVOKE_DEVICE","PREVIEW","FINAL_RENDER"]),phase:z.enum(["PREPARED","SENDING","REFUSED"]),fingerprint:digest}).nullable()});var DesktopDeviceReplySchema=z.strictObject({view:DesktopDeviceViewSchema,command:LocalManagementCommandSchema.optional(),mediaValidationSupported:z.boolean().optional(),mediaProcessingSupported:z.boolean().optional(),localLibrarySupported:z.boolean().optional(),compositionProcessingSupported:z.boolean().optional()});import{join}from"node:path";var recordRoot=(home,scope)=>join(home,"devices",sha256(canonicalLocalJson(scope)));var DesktopDeviceRecords=class _DesktopDeviceRecords{constructor(root,scope){this.root=root;this.scope=scope}root;scope;static async open(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);return new _DesktopDeviceRecords(await directory(recordRoot(home,scope)),scope)}static async inspect(home,raw){const scope=DesktopDeviceScopeSchema.parse(raw);const root=recordRoot(home,scope);try{await privateAccess(join(home,"devices"),"directory");await privateAccess(root,"directory")}catch(error){if(error.code==="ENOENT")return null;throw error}return new _DesktopDeviceRecords(root,scope).current()}async current(){const names=(await entries(this.root)).filter(n=>/^\d{12}\.json$/.test(n)).sort();let state={revision:0,scope:this.scope,enrollment:null,device:null,previews:[],connectorId:null,connection:null,pending:null};for(const[index,name]of names.entries()){const next=DesktopDeviceStateSchema.parse(JSON.parse((await read(join(this.root,name),262144,true)).toString()));if(next.revision!==index+1||canonicalLocalJson(next.scope)!==canonicalLocalJson(this.scope))fail("DEVICE_HISTORY_INVALID");state=next}return state}async save(before,fields){if((await this.current()).revision!==before.revision)fail("REVISION_CONFLICT");const next=DesktopDeviceStateSchema.parse({...before,...fields,revision:before.revision+1});try{await write(join(this.root,String(next.revision).padStart(12,"0")+".json"),canonicalLocalJson(next),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return next}keyPath(){return join(this.root,"device-key.json")}connectorPath(id){return join(this.root,id+".connector.json")}};async function desktopDeviceConnector(home,scope){const records=await DesktopDeviceRecords.open(home,scope),state=await records.current();if(!state.connectorId)fail("LOCAL_AUTHORIZATION_REQUIRED");return records.connectorPath(state.connectorId)}export{DesktopDeviceScopeSchema,DesktopDeviceRequestSchema,DesktopDeviceReplySchema,DesktopDeviceRecords,desktopDeviceConnector};
|
|
@@ -1 +1 @@
|
|
|
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};
|
|
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-A7EUJNCL.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],...match[2]?{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"||account.workspaceId!==scope.tenantId||scope.projectId&&account.projectId!==scope.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");await write(join3(root,"connection.json"),JSON.stringify({version:scope.projectId?account?2:1:3,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){void verifyAccount;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(![1,2,3].includes(Number(value.version))||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(value.version===3===Boolean(scope.projectId))connectionError("CONNECTION_SCOPE_MISMATCH");if(scope.tenantId!==value.tenantId||scope.projectId!==value.projectId)connectionError("CONNECTION_SCOPE_MISMATCH");const account=await readAccount(root);if((value.version===2||value.accountEpoch!==void 0)&&(!account||typeof value.accountEpoch!=="string"))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&(value.version!==(scope.projectId?2:3)||account.state!=="ACTIVE"||value.accountEpoch!==account.epoch||scope.tenantId!==account.workspaceId||scope.projectId&&scope.projectId!==account.projectId))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:value.projectId?"PROJECT_MCP":"TENANT_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 <workspace-connection-url>."]:["nvs find --query <intent>","nvs capabilities","nvs mcp"]}:{semanticStatus:"NEEDS_INPUT",connected:false,credentialPurpose:"TENANT_MCP",accountSessionVerified:false,nextSteps:["Open Agent access in the workspace settings, then authorize the workspace once.","nvs connect --mcp-url <workspace-connection-url>"]}}}export{connectionError,clientHome,accountServerOrigin,NativeStudioAccountClient,accountError,readAccount,saveAccount,withAccountLock,requireAccount,projectConnection,saveConnection,loadConnection,defaultConnection,connectionStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{workspaceProject}from"./chunk-XRYARPEL.js";import{clientHome,loadConnection,projectConnection,readAccount}from"./chunk-TCZJLYSR.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import{readCredential}from"./chunk-6LU6GJKW.js";import{sha256}from"./chunk-KB2GVAN7.js";import{connectRemoteMcp}from"./chunk-6SYHA2B4.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";async function selectedProject(scope,env,explicit){if(scope.projectId){if(explicit&&explicit!==scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return scope.projectId}if(explicit)return z.uuid().parse(explicit);const selected=await workspaceProject(scope,env);if(selected)return selected;const account=await readAccount(await clientHome(env));const projectId=explicit??(account?.workspaceId===scope.tenantId?account.projectId:null);if(!projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return z.uuid().parse(projectId)}async function renderConnection(env,signal,write=true,projectId){const scope=await loadConnection(env,true);if(!scope||write&&!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");const selected=await selectedProject(scope,env,projectId);return{scope:{...scope,projectId:selected},...await connectRemoteMcp(scope.resource,auth.authorization,scope.tenantId)}}async function callerRenderConnection(env,flags,write=true){const url=flags.get("--mcp-url");if(!url&&!flags.has("--token-file"))return renderConnection(env,void 0,write,flags.get("--project"));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,projectId:await selectedProject(scope,env,flags.get("--project")),profile:"grant:"+sha256(auth)},...await connectRemoteMcp(scope.resource,auth,scope.tenantId)}}export{selectedProject,renderConnection,callerRenderConnection};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{profileHttpOrigin}from"./chunk-RJ4QQF7E.js";import{selectedProject}from"./chunk-TTFDNLQE.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-TCZJLYSR.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import{connectRemoteMcp}from"./chunk-6SYHA2B4.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";async function resolveCaller(env,explicitProject,workspaceOnly=false){const home=await clientHome(env),account=await readAccount(home);const saved=await loadConnection(env,true);const assertCurrent=async()=>{const latest=await loadConnection(env,true),current=await readAccount(home);if(latest?.profile!==saved?.profile||latest?.resource!==saved?.resource||account?.epoch!==current?.epoch||account?.state!==current?.state||account?.principalId!==current?.principalId||account?.workspaceId!==current?.workspaceId||account?.serverOrigin!==current?.serverOrigin)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(latest?.exchangeUnresolved)throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","BLOCKED","UNKNOWN");if(account&&(!saved||saved.projectId))requireAccount(current)};if(saved&&!saved.projectId){const auth=await profileAuthorization(saved.profile);if(auth.resource!==saved.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const projectId=workspaceOnly?void 0:await selectedProject(saved,env,explicitProject);const c=await connectRemoteMcp(saved.resource,auth.authorization,saved.tenantId);try{const caller=await c.studio.call("workspace.caller",{});if(caller.tenantId!==saved.tenantId||account&&(account.principalId!==caller.principalId||account.serverOrigin!==caller.serverOrigin))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(projectId){const selected=await c.studio.call("project.get",{projectId});if(selected.project.id!==projectId||selected.project.tenantId!==caller.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}await assertCurrent();return{...caller,home,projectId,resource:saved.resource,profile:saved.profile,assertCurrent}}finally{await c.close().catch(()=>{})}}if(saved?.projectId&&!account)throw new NativeStudioSdkError("TENANT_CONNECTION_REQUIRED","BLOCKED","NO_WRITE");if(!account)return null;const human=requireAccount(account);if(saved?.projectId&&explicitProject&&saved.projectId!==explicitProject)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");if(!human.workspaceId||!workspaceOnly&&!(explicitProject??human.projectId))throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{home,tenantId:human.workspaceId,projectId:workspaceOnly?void 0:z.uuid().parse(explicitProject??human.projectId),principalId:human.principalId,serverOrigin:human.serverOrigin,resource:saved?.resource,profile:saved?.profile,assertCurrent}}async function localCaller(env,explicitProject){const caller=await resolveCaller(env,explicitProject);if(!caller)return null;if(!caller.projectId)throw new NativeStudioSdkError("PROJECT_SELECTION_REQUIRED","BLOCKED","NO_WRITE");return{...caller,projectId:caller.projectId}}function workspaceCaller(env){return resolveCaller(env,void 0,true)}async function callerOriginMatches(origin,caller){if(origin===caller.serverOrigin)return true;if(!caller.resource||!caller.profile)return false;return origin===new URL(caller.resource).origin||origin===await profileHttpOrigin(caller.profile,caller.resource)}export{localCaller,workspaceCaller,callerOriginMatches};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{clientHome,loadConnection}from"./chunk-TCZJLYSR.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import{optional,write}from"./chunk-KB2GVAN7.js";import{connectRemoteMcp}from"./chunk-6SYHA2B4.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{join}from"node:path";import{z}from"zod";var selection=z.strictObject({version:z.literal(1),tenantId:z.uuid(),resource:z.url(),projectId:z.uuid()});async function workspaceProject(scope,env){const value=await optional(join(await clientHome(env),"selection.json"));if(value===null)return null;const parsed=selection.safeParse(value);if(!parsed.success)throw new NativeStudioSdkError("PROJECT_SELECTION_INVALID","BLOCKED","NO_WRITE");return parsed.data.tenantId===scope.tenantId&&(!scope.resource||parsed.data.resource===scope.resource)?parsed.data.projectId:null}async function workspaceCommand(argv,env){const[command,...args]=argv;if(!["workspaces","workspace","projects","project"].includes(command??""))return null;let connection;try{connection=await loadConnection(env,true)}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="PROJECT_CONNECTION_ACCOUNT_MISMATCH")return null;throw error}if(!connection||connection.projectId)return null;const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!value||value.startsWith("--")||flags.has(key)||!["--id","--limit","--next"].includes(key))throw Error();flags.set(key,value)}if(command==="projects"?flags.has("--id"):command==="workspaces"?flags.size>0:flags.size!==1||!flags.has("--id"))throw Error();const auth=await profileAuthorization(connection.profile);const remote=await connectRemoteMcp(connection.resource,auth.authorization,connection.tenantId);try{if(command==="workspaces"){const page=await remote.studio.call("workspace.query",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaces:page.items}}}if(command==="projects"){const page=await remote.studio.call("project.query",{...flags.has("--limit")?{limit:z.coerce.number().int().min(1).max(100).parse(flags.get("--limit"))}:{},...flags.has("--next")?{next:flags.get("--next")}:{}});return{exitCode:0,output:{semanticStatus:"SUCCESS",...page}}}const id=z.uuid().parse(flags.get("--id"));if(command==="workspace"){if(id!==connection.tenantId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value2=await remote.studio.call("workspace.get",{});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:value2.id}}}const value=await remote.studio.call("project.get",{projectId:id});await write(join(await clientHome(env),"selection.json"),JSON.stringify({version:1,tenantId:connection.tenantId,resource:connection.resource,projectId:value.project.id}));return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project}}}finally{await remote.close().catch(()=>{})}}export{workspaceProject,workspaceCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defaultConnection,projectConnection}from"./chunk-TCZJLYSR.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import{connectRemoteMcp}from"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var operations={enroll:"device.enroll",revoke:"device.revoke",receipt:"device.management-receipt"};async function deviceManagementCommand(action,args,env,stdin){if(!action||!Object.hasOwn(operations,action))throw Error();const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--input","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}if(!flags.has("--input"))throw Error();await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(k=>flags.has(k)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=projectConnection(resource);if(scope.projectId)throw new NativeStudioSdkError("TENANT_CONNECTION_REQUIRED","BLOCKED","NO_WRITE");const raw=await readInput(flags.get("--input"),stdin);const nested=action==="receipt"?raw.input:raw;if(nested?.tenantId!==void 0&&String(nested.tenantId).toLowerCase()!==scope.tenantId.toLowerCase())throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const key=operations[action];const input=action==="receipt"?{command:raw}:{...raw,tenantId:scope.tenantId};const output=await connection.studio.call(key,input);return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceManagementCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{callerOriginMatches,workspaceCaller}from"./chunk-URKX77KR.js";import"./chunk-RJ4QQF7E.js";import{renderConnection}from"./chunk-TTFDNLQE.js";import{LocalInstallationManager,ownerClient,probeLocalLibrary,probeTenantComposition,probeTenantMediaProcessing,probeTenantMediaValidation,probeTenantQwenGeneration,probeTenantSpeech,probeTenantTranscription,verifySlot}from"./chunk-LUBHPAPW.js";import{DesktopDeviceRecords}from"./chunk-SIJPJIBO.js";import"./chunk-JH5QP6PC.js";import"./chunk-XRYARPEL.js";import"./chunk-TCZJLYSR.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import{LocalClientError,read}from"./chunk-KB2GVAN7.js";import"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import{LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema}from"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";var transportSchema=LocalDeviceTransportConfigurationSchema.safeExtend({tools:LocalToolSelectionSchema.optional()});var nextSteps={ACCOUNT_LOGIN_REQUIRED:"nvs login --server <Studio-origin>",TENANT_CONNECTION_REQUIRED:"nvs connect --mcp-url <tenant-connection-url>",ACCOUNT_REVOCATION_UNCONFIRMED:"nvs logout",PROJECT_SELECTION_REQUIRED:"Run nvs workspaces, nvs projects, then nvs project --id <project-id>",INSTALL_REQUIRED:"Configure the Runtime, check signed releases, then prepare nvs local install --version <exact>",INSTALLATION_RECOVERY_REQUIRED:"Inspect nvs local status, then reconcile the original installation plan",CONFIGURATION_REQUIRED:"nvs local configure --input <private-json>",DEVICE_ENROLLMENT_REQUIRED:"nvs local cloud --action enroll with the approved owner input",DEVICE_RECEIPT_REQUIRED:"nvs local cloud --action receipt with the original management command",PROJECT_CONNECTION_REQUIRED:"nvs connect",DEVICE_AUTHORITY_UNCONFIRMED:"Check the current workspace membership, device proof and revocation",DEVICE_CONNECTION_REQUIRED:"nvs local connect --input <private-device-config>",DEVICE_CONNECTION_RECOVERY_REQUIRED:"Inspect the original device connection and Runtime status",DEVICE_OFFLINE:"Inspect nvs local status, then start the configured Runtime if stopped",DEVICE_BUSY:"Wait for available capacity, then recheck this device",RUNTIME_QUALIFICATION_REQUIRED:"Check the signed Runtime slot and the approved tools",DEVICE_CAPABILITY_UNCONFIRMED:"Check the configured action, tool or provider prerequisites and the current heartbeat",PROJECT_QUERY_UNAVAILABLE:"Check the selected Project connection, then retry this read"};async function qualified(kind,root,slot,validator){if(kind==="library")return true;if(kind==="preview"||kind==="final")return validator?probeTenantMediaValidation(root,slot):true;if(!await probeTenantMediaProcessing(root,slot))return false;switch(kind){case"LOCAL_MEDIA_INSPECT":case"LOCAL_MEDIA_PUBLISH":return probeLocalLibrary(root,slot);case"COMPOSITION_RENDER":return probeTenantComposition(root,slot);case"SPEECH_SYNTHESIZE":return probeTenantSpeech(root,slot);case"TRANSCRIBE_AUDIO":return probeTenantTranscription(root,slot);case"KEYFRAME_GENERATE":return probeTenantQwenGeneration(root,slot,"keyframe");case"VIDEO_GENERATE":return probeTenantQwenGeneration(root,slot,"video");case"SPEECH_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"speech");case"TRANSCRIBE_EXTERNAL_QWEN":return probeTenantQwenGeneration(root,slot,"asr");default:return true}}async function devicePreflight(raw,env,explicitProject){const kind=DeviceDiscoveryInputSchema.shape.kind.parse(raw);const context={};const blocked=reason=>({exitCode:4,output:{semanticStatus:"BLOCKED",kind,...context,error:{code:reason,outcome:"NO_WRITE"},nextStep:nextSteps[reason]}});let caller;try{caller=await workspaceCaller(env)}catch(error){if(error.code==="ENOENT")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error instanceof NativeStudioSdkError){if(error.code==="TENANT_CONNECTION_REQUIRED")return blocked("TENANT_CONNECTION_REQUIRED");if(error.code==="ACCOUNT_LOGIN_REQUIRED")return blocked("ACCOUNT_LOGIN_REQUIRED");if(error.code==="ACCOUNT_LOGOUT_OUTCOME_UNKNOWN")return blocked("ACCOUNT_REVOCATION_UNCONFIRMED");if(error.code==="PROJECT_SELECTION_REQUIRED")return blocked("PROJECT_SELECTION_REQUIRED")}throw error}if(!caller)return blocked("ACCOUNT_LOGIN_REQUIRED");const{home,tenantId,principalId,serverOrigin}=caller;const projectId=explicitProject?z.uuid().parse(explicitProject):void 0;Object.assign(context,{tenantId,projectId});const manager=await LocalInstallationManager.openExisting(home);if(!manager)return blocked("INSTALL_REQUIRED");const{active,transition}=(await manager.ledger.current()).value;if(transition)return blocked("INSTALLATION_RECOVERY_REQUIRED");if(!active)return blocked("INSTALL_REQUIRED");const slotRoot=manager.ledger.slotPath(active);await verifySlot(slotRoot,active);const records=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});const pending=records?.pending?.command;if(records?.pending?.phase==="SENDING"&&(pending?.kind==="ENROLL"||pending?.kind==="REVOKE_DEVICE"))return blocked("DEVICE_RECEIPT_REQUIRED");if(records?.connection?.phase==="CONNECTING")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const config=await manager.configuration().catch(error=>{if(error instanceof LocalClientError&&error.code==="CONFIGURATION_REQUIRED")return null;throw error});if(!config)return blocked("CONFIGURATION_REQUIRED");let transport=null;try{if(config.cloudConfigFile)transport=transportSchema.parse(JSON.parse((await read(config.cloudConfigFile,32768)).toString()))}catch(error){if(error.code==="ENOENT")return blocked("DEVICE_CONNECTION_REQUIRED");if(error instanceof SyntaxError||error instanceof z.ZodError)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");throw error}const endpoint=transport?new URL(transport.endpoint):null;const current=endpoint&&await callerOriginMatches(endpoint.origin,caller)&&!endpoint.username&&!endpoint.password&&transport?.tenantId===tenantId?transport:null;const deviceId=records?.device?.deviceId??current?.deviceId;if(!deviceId)return blocked("DEVICE_ENROLLMENT_REQUIRED");context.deviceId=deviceId;const configured=current?.deviceId===deviceId&¤t.tenantId===tenantId;if(!configured||!current)return blocked("DEVICE_CONNECTION_REQUIRED");if(!projectId){const local=await ownerClient(config.stateDirectory);const status=await local.status(void 0,true).catch(()=>null);if(!status)return blocked("DEVICE_OFFLINE");if(status.deviceAuthority?.tenantId!==tenantId||status.deviceAuthority.deviceId!==deviceId)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(status.state==="DRAINING")return blocked("DEVICE_BUSY");if(status.state==="RECOVERY_REQUIRED")return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");const capabilities=status.deviceCapabilities;if(!capabilities)return blocked("DEVICE_CAPABILITY_UNCONFIRMED");if(capabilities.deviceRevision!==current.deviceRevision)return blocked("DEVICE_CONNECTION_RECOVERY_REQUIRED");if(kind!=="preview"&&kind!=="final"&&kind!=="library"){const configuredKinds=current.processorCapabilities??[];if(!current.tenantMediaProcessing||!configuredKinds.includes(kind)||!capabilities.tenantMediaProcessing||!capabilities.processorCapabilities.includes(kind))return blocked("DEVICE_CAPABILITY_UNCONFIRMED")}if(!await qualified(kind,slotRoot,active,!!current?.tenantMediaValidation))return blocked("RUNTIME_QUALIFICATION_REQUIRED");await caller.assertCurrent();return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,deviceId,availability:status.state==="EXECUTING"?"BUSY":"AVAILABLE"}}}const conn=await renderConnection(env,void 0,false,projectId).catch(error=>{if(error instanceof NativeStudioSdkError&&error.code==="AUTHORIZATION_REQUIRED")return null;throw error});if(!conn)return blocked("PROJECT_CONNECTION_REQUIRED");try{if(conn.scope.tenantId!==tenantId||conn.scope.projectId!==projectId||(caller.resource?conn.scope.resource!==caller.resource:new URL(conn.scope.resource).origin!==serverOrigin))return blocked("PROJECT_CONNECTION_REQUIRED");const page=await conn.studio.deviceRenders.list({kind,projectId,deviceId}).catch(error=>{if(error instanceof NativeStudioSdkError)return null;throw error});await caller.assertCurrent();if(!page||page.truncated)return blocked("PROJECT_QUERY_UNAVAILABLE");const candidate=page.items[0];if(!candidate)return blocked("DEVICE_AUTHORITY_UNCONFIRMED");if(!configured)return blocked("DEVICE_CONNECTION_REQUIRED");if(candidate.availability==="OFFLINE")return blocked("DEVICE_OFFLINE");if(candidate.availability==="BUSY")return blocked("DEVICE_BUSY");if(candidate.availability==="UNQUALIFIED")return blocked(await qualified(kind,slotRoot,active,!!page.validationMode)?"DEVICE_CAPABILITY_UNCONFIRMED":"RUNTIME_QUALIFICATION_REQUIRED");return{exitCode:0,output:{semanticStatus:"SUCCESS",kind,tenantId,projectId,deviceId,availability:candidate.availability,validationMode:page.validationMode}}}finally{await conn.close().catch(()=>{})}}export{devicePreflight};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defaultConnection,projectConnection}from"./chunk-TCZJLYSR.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import{readCredential}from"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import{connectRemoteMcp}from"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import{WorkspaceDeviceListInputSchema}from"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var query=WorkspaceDeviceListInputSchema.omit({tenantId:true});async function deviceInventoryCommand(args,env){const flags=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--device","--after","--limit","--profile","--mcp-url","--token-file","--token-env"].includes(key)||!value||value.startsWith("--")||flags.has(key))throw Error();flags.set(key,value)}const input=query.parse({...flags.has("--device")&&{deviceId:flags.get("--device")},...flags.has("--after")&&{after:flags.get("--after")},...flags.has("--limit")&&{limit:Number(flags.get("--limit"))}});await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile&&["--mcp-url","--token-file","--token-env"].some(key=>flags.has(key)))throw Error();const token=profile?await profileAuthorization(profile):null;const resource=token?.resource??flags.get("--mcp-url");if(!resource)throw Error();const scope=projectConnection(resource);if(scope.projectId)throw new NativeStudioSdkError("TENANT_CONNECTION_REQUIRED","BLOCKED","NO_WRITE");const authorization=token?.authorization??await readCredential(flags,env);const connection=await connectRemoteMcp(scope.resource,authorization,scope.tenantId);try{const output=await connection.studio.call("workspace.devices.list",{...input,tenantId:scope.tenantId});return{exitCode:0,output}}finally{await connection.close().catch(()=>{})}}export{deviceInventoryCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{callerRenderConnection}from"./chunk-TTFDNLQE.js";import"./chunk-XRYARPEL.js";import"./chunk-TCZJLYSR.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import"./chunk-6NVIN2NI.js";var query=DeviceDiscoveryInputSchema.pick({kind:true,deviceId:true});async function devicesCommand(argv,env,stdin=process.stdin){const[action,...args]=argv;if(action==="inventory")return(await import("./devices-inventory-RVHGI2YW.js")).deviceInventoryCommand(args,env);if(action!=="list")return(await import("./device-management-4XIITODX.js")).deviceManagementCommand(action,args,env,stdin);const flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--kind","--device","--project","--mcp-url","--token-file"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}const input=query.parse({kind:flags.get("--kind"),...flags.has("--device")&&{deviceId:flags.get("--device")}});const conn=await callerRenderConnection(env,flags,false);try{const output=await conn.studio.deviceRenders.list({...input,projectId:conn.scope.projectId});return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{devicesCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{profileHttpOrigin}from"./chunk-RJ4QQF7E.js";import"./chunk-TCZJLYSR.js";import"./chunk-FU3524Z6.js";import"./chunk-KB2GVAN7.js";import"./chunk-A7EUJNCL.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import"./chunk-6NVIN2NI.js";export{profileHttpOrigin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{localCaller}from"./chunk-URKX77KR.js";import"./chunk-RJ4QQF7E.js";import{renderConnection}from"./chunk-TTFDNLQE.js";import{DesktopLibraryImportSeedSchema,prepareDesktopLibraryImport,runDesktopLibraryImport,runDesktopLibraryRequest}from"./chunk-LF442QV6.js";import"./chunk-LUBHPAPW.js";import{DesktopDeviceRecords}from"./chunk-SIJPJIBO.js";import"./chunk-JH5QP6PC.js";import"./chunk-XRYARPEL.js";import"./chunk-TCZJLYSR.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import{readInput}from"./chunk-6LU6GJKW.js";import{fail,sha256}from"./chunk-KB2GVAN7.js";import"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import{LocalDeviceViewSchema,LocalManagementCommandSchema}from"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{homedir}from"node:os";import{join,resolve,basename}from"node:path";async function libraryImportContext(home,raw,enrollment){const caller=await localCaller({...process.env,NATIVESTUDIO_CLIENT_HOME:home},typeof raw.projectId==="string"?raw.projectId:void 0);if(!caller){if(!["tenantId","projectId","deviceId","ownerKey"].every(key=>raw[key]))fail("ACCOUNT_LOGIN_REQUIRED");return{}}const{serverOrigin,tenantId,principalId,projectId}=caller;const ownerKey=sha256(JSON.stringify([serverOrigin,tenantId,principalId]));const denied=()=>{throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")};if(raw.tenantId!==void 0&&raw.tenantId!==tenantId||raw.projectId!==void 0&&raw.projectId!==projectId||raw.ownerKey!==void 0&&raw.ownerKey!==ownerKey)denied();const record=await DesktopDeviceRecords.inspect(home,{origin:serverOrigin,tenantId,principalId});if(record?.device&&(record.device.enrolledByPrincipalId!==principalId||record.device.tenantId!==tenantId))denied();if(record?.pending?.phase==="SENDING")fail("DEVICE_RECEIPT_REQUIRED");let deviceId=record?.device?.deviceId;if(!deviceId&&enrollment!==void 0){const command=LocalManagementCommandSchema.parse(enrollment);if(command.kind!=="ENROLL"||command.input.tenantId!==tenantId)denied();const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const c=await renderConnection(env,void 0,false,projectId);try{if(c.scope.profile!==caller.profile||c.scope.resource!==caller.resource)denied();const receipt=await c.studio.call("device.management-receipt",{command});if(!receipt.result)fail("DEVICE_RECEIPT_REQUIRED");const device=LocalDeviceViewSchema.parse(receipt.result);if(device.enrolledByPrincipalId!==principalId||device.tenantId!==tenantId)denied();deviceId=device.deviceId}finally{await c.close().catch(()=>{})}}if(!deviceId)fail("DEVICE_SETUP_REQUIRED");if(raw.deviceId!==void 0&&raw.deviceId!==deviceId)denied();await caller.assertCurrent();return{tenantId,projectId,deviceId,ownerKey,assertCurrent:caller.assertCurrent}}async function runLocalLibrary(argv,stdin){const[action,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const name=args[i],value=args[i+1];if(!name||!["--home","--input","--file","--enrollment"].includes(name)||!value||value.startsWith("--")||flags.has(name))throw Error();flags.set(name,value)}if(!action||!["import","list","get","read","access","sync","resume-access","import-receipt","usage"].includes(action)||!flags.has("--input")||flags.get("--input")==="-"&&flags.get("--enrollment")==="-"||action!=="import"&&(flags.has("--file")||flags.has("--enrollment")))throw Error();const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio/client"));const raw=await readInput(flags.get("--input"),stdin);if(action!=="import")return{exitCode:0,output:await runDesktopLibraryRequest(home,{operation:"library",call:{...raw,action}})};const file=flags.get("--file");if(!file)throw Error();const enrollment=flags.has("--enrollment")?await readInput(flags.get("--enrollment"),stdin):void 0;const{assertCurrent,...defaults}=await libraryImportContext(home,raw,enrollment);const seed=DesktopLibraryImportSeedSchema.parse({...defaults,title:basename(file),contentType:"application/octet-stream",...raw});const request=await prepareDesktopLibraryImport({operation:"library-import-prepare",file:resolve(file),seed});await assertCurrent?.();return{exitCode:0,output:await runDesktopLibraryImport(home,request)}}export{runLocalLibrary};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{connectDevice,generateDeviceKey}from"./chunk-OZ5KZSTM.js";import{LocalInstallationManager,captureInstalledTools,ownerClient}from"./chunk-LUBHPAPW.js";import{NativeStudioLocalDeviceClient}from"./chunk-JH5QP6PC.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{LocalClientError}from"./chunk-KB2GVAN7.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioAgentClient}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import{EnrollLocalDeviceSchema,LocalAgentGrantSchema,LocalManagementCommandSchema,RevokeLocalDeviceSchema,StartLocalFinalRenderSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentMediaProposal,localAgentMediaSnapshot,localAgentSnapshotFromContext}from"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{homedir as homedir2}from"node:os";import{join as join2,resolve as resolve2}from"node:path";import{homedir}from"node:os";import{join,resolve}from"node:path";import{createHash}from"node:crypto";async function runLocalAgentCli(argv,stdin){try{const[command,...rest]=argv,flags=new Map;for(let n=0;n<rest.length;n+=2){const k=rest[n],v=rest[n+1];if(!k||!["--home","--input","--approve","--id","--revision","--evidence","--origin","--token-file"].includes(k)||!v||v.startsWith("--")||flags.has(k))throw Error();flags.set(k,v)}const need=k=>{const v=flags.get(k);if(!v)throw Error();return v};if(command==="agent-grant-plan"){const grant=LocalAgentGrantSchema.parse(await readInput(need("--input"),stdin));const disclosures=["review metadata",...grant.imageDisclosureApproved?["original image pixels"]:[],...grant.mediaDisclosureApproved?["normalized image pixels or sampled video frames and technical audio statistics"]:[]];return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:`Approving this fingerprint permits remote OpenAI inference for these Projects until expiry and allows disclosure of ${disclosures.join(", ")}. Preview does not invoke a model.`}}}const evidence=flags.get("--evidence");if(evidence&&!["IMAGE_PIXELS","METADATA_ONLY","MEDIA"].includes(evidence))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);const studioFor=tenantId=>new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId,authorization:()=>readCredential(flags,process.env)});let output;switch(command){case"agent-grant":output=await client.grantAgent(await readInput(need("--input"),stdin),need("--approve"));break;case"agent-revoke":output=await client.revokeAgent(need("--approve"));break;case"agent-probe":output=await client.probeAgent();break;case"review-prepare":{const context=await readInput(need("--input"),stdin);output=await client.prepareAgentReview(evidence==="MEDIA"?localAgentMediaSnapshot(context):localAgentSnapshotFromContext(context,evidence==="IMAGE_PIXELS"));break}case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image||snapshot.basis.target.kind!=="IMAGE")throw Error();const studio=studioFor(snapshot.basis.scope.tenantId);const media=await studio.keyframeMedia({productionId:snapshot.basis.scope.productionId,generationId:snapshot.basis.target.generationId},{checksumSha256:snapshot.media.checksumSha256,byteSize:snapshot.image.byteSize});if(media.contentType!==snapshot.image.contentType)throw Error();output=await client.stageAgentImage(view.plan.id,media.bytes);break}case"review-media-fetch":{const view=await client.inspectAgentReview(need("--id"));const{basis,evidence:expected,media}=view.plan.snapshot;if(!expected)throw Error();if(view.evidenceReceipt){output=view;break}if(view.phase!=="PREPARED")throw Error();const source=await studioFor(basis.scope.tenantId).immutableMedia({projectId:basis.scope.projectId,representationId:media.representationId,checksumSha256:media.checksumSha256,byteSize:expected.byteSize});output=await client.stageAgentImage(view.plan.id,source.bytes);break}case"review-start":output=await client.startAgentReview(need("--id"),Number(need("--revision")),need("--approve"));break;case"review-inspect":output=await client.inspectAgentReview(need("--id"));break;case"review-proposal":output=localAgentMediaProposal(await client.inspectAgentReview(need("--id")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof NativeStudioSdkError;return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known?e.code:"INVALID_INPUT",outcome:known?e.outcome:"NO_WRITE"}}}}}async function runLocalCli(argv,stdin=process.stdin){let mutation=false;try{const[command,...rest]=argv,options=new Map;if(command==="library"){mutation=["import","access","resume-access"].includes(rest[0]??"");return await(await import("./library-main-ZQKJQNHE.js")).runLocalLibrary(rest,stdin)}if(command==="device-preflight"){for(let i=0;i<rest.length;i+=2){const name=rest[i],value=rest[i+1];if(!name||!["--kind","--home","--project"].includes(name)||!value||value.startsWith("--")||options.has(name))throw Error();options.set(name,value)}return(await import("./device-preflight-SDA7Q3LH.js")).devicePreflight(options.get("--kind"),{...process.env,...options.has("--home")&&{NATIVESTUDIO_CLIENT_HOME:resolve2(options.get("--home"))}},options.get("--project"))}if(command?.startsWith("agent-")||command?.startsWith("review-"))return runLocalAgentCli(argv,stdin);const allowed=["--home","--input","--version","--plan","--approve","--output","--origin","--token-file","--action"];for(let i=0;i<rest.length;i+=2){const k=rest[i],v=rest[i+1];if(!k||!allowed.includes(k)||!v||v.startsWith("--")||options.has(k))throw Error();options.set(k,v)}if(command==="help"||!command)return{exitCode:0,output:{namespace:"nvs local",commands:["configure --input <private-json>","keygen --output <new-private-device-key>","cloud --action enroll|revoke-device|preview|final|receipt --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact>","tools-prepare --version <exact> --input <private-json with mode MANAGED or INSTALLED and exact ffmpeg/ffprobe paths, optional Linux x64 compositionBrowser>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","device-preflight --kind preview|final|<processor-kind> [--project <uuid>] [--home <private-client-home>] \u2014 read current setup and action qualification","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp [--connector <private-file>] [--with-project-renders] [--with-library]","library import|list|get|read|access|sync|resume-access|import-receipt|usage --input <json|-> [--file <exact-media>] [--home <client-home>] \u2014 private Owner library; import never uploads","agent-grant-plan|agent-probe|agent-grant|agent-revoke \u2014 installed Codex CLI with explicitly authorized remote OpenAI inference","review-prepare --input <private-context> [--evidence METADATA_ONLY|IMAGE_PIXELS|MEDIA]","review-media-fetch --id <draft> --origin <cloud-origin> --token-file <member-token> \u2014 read exact stored bytes for a MEDIA draft","review-image-fetch|review-inspect|review-proposal \u2014 use --id <draft>","review-start --id <draft> --revision <current> --approve <plan-fingerprint>"],note:"Check/prepare do not download executables. Apply requires exact approval. MCP disconnect does not stop Runtime."}};if(command==="version")return{exitCode:0,output:await localCliVersion()};const required=key=>{const v=options.get(key);if(!v)throw Error();return v};if(command==="keygen")return{exitCode:0,output:await generateDeviceKey(resolve2(required("--output")))};if(command==="cloud"){const input=await readInput(required("--input"),stdin);const action=required("--action");const tenantId=action==="receipt"?LocalManagementCommandSchema.parse(input).input.tenantId:input.tenantId;if(typeof tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):action==="final"?await client.startFinal(StartLocalFinalRenderSchema.parse(input)):action==="receipt"?await client.managementReceipt(LocalManagementCommandSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const manager=await LocalInstallationManager.open(resolve2(options.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join2(homedir2(),".nativestudio","client")));let output;mutation=["configure","connect","start","stop","grant","update-apply","update-reconcile","update-reject"].includes(command??"");switch(command){case"connect":output=await connectDevice(manager,await readInput(required("--input"),stdin));break;case"configure":output=await manager.configure(await readInput(required("--input"),stdin));break;case"status":output=await manager.status();break;case"update-reject":output=await manager.reject(required("--version"));break;case"update-check":output=await manager.check();break;case"install":case"update-prepare":output=await manager.prepare(required("--version"));break;case"tools-prepare":{const raw=await readInput(required("--input"),stdin);const choice=raw.mode==="INSTALLED"?await captureInstalledTools(raw):raw;output=await manager.prepare(required("--version"),choice)}break;case"update-apply":output=await manager.apply(required("--plan"),required("--approve"));break;case"update-reconcile":output=await manager.reconcile(required("--plan"),required("--approve"));break;case"start":output=await manager.start();break;case"stop":output=await manager.stop();break;case"doctor":output=await(await ownerClient((await manager.configuration()).stateDirectory)).doctor();break;case"grant":output=await manager.grant(await readInput(required("--input"),stdin),resolve2(required("--output")));break;default:throw Error()}return{exitCode:0,output}}catch(e){const known=e instanceof LocalClientError?e.code:e instanceof NativeStudioSdkError?e.code:"INVALID_INPUT";return{exitCode:2,output:{semanticStatus:"BLOCKED",error:{code:known,outcome:e instanceof NativeStudioSdkError?e.outcome:mutation&&!["USER_APPROVAL_REQUIRED","PLAN_CHANGED","REVISION_CONFLICT","INSTALL_REQUIRED","CONFIGURATION_REQUIRED"].includes(known)?"UNKNOWN":"NO_WRITE"}}}}}export{runLocalCli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{StdioLines}from"./chunk-JFC6ZIGA.js";import{assertRenderProject}from"./chunk-DRHPICBU.js";import{renderConnection,selectedProject}from"./chunk-TTFDNLQE.js";import{LocalMcpTools,localTools}from"./chunk-AJ7S73M4.js";import{desktopDeviceConnector}from"./chunk-SIJPJIBO.js";import"./chunk-JH5QP6PC.js";import"./chunk-XRYARPEL.js";import{clientHome,loadConnection,readAccount,requireAccount}from"./chunk-TCZJLYSR.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-6SYHA2B4.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,PreparedDeviceRenderSchema}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import{FinalRenderViewSchema,LocalMcpFailureSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema}from"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{homedir}from"node:os";import{join,resolve}from"node:path";import{deserializeMessage,SUPPORTED_PROTOCOL_VERSIONS,LATEST_PROTOCOL_VERSION,serializeMessage,isJSONRPCRequest,isJSONRPCNotification}from"@modelcontextprotocol/client";import{z}from"zod";var templates={local_devices_list:{description:"Read the selected Project's exact candidate result for this device and render or processor kind. Use the Project connection to discover other devices; use owner CLI device-preflight for local setup prerequisites.",input:DeviceDiscoveryInputSchema.pick({kind:true}),output:ProjectDeviceListSchema},local_render_get:{description:"Read the exact native preview or final render in this authorized Project.",input:DeviceRenderReadSchema,output:z.union([RoughCutViewSchema,FinalRenderViewSchema])},local_render_media_ticket:{description:"Read a short-lived direct storage ticket for an exact accepted Project render.",input:DeviceRenderDownloadSchema,output:TenantRenderMediaTicketSchema},local_render_receipt:{description:"Look up a previously submitted native render using the exact prepared command. This performs no write.",input:PreparedDeviceRenderSchema,output:DeviceRenderAdmissionSchema},local_render_prepare:{description:"Read the selected Project's exact current preview/final basis for this computer with Project write scope. Preserve this command for submission and reconciliation.",input:DeviceRenderIntentSchema,output:PreparedDeviceRenderSchema},local_render_start:{description:"Submit an exact prepared preview/final to this authorized tenant computer only. Offline means unavailable. Keep the operation and job identities; never resubmit an unknown write.",input:PreparedDeviceRenderSchema,output:DeviceRenderAdmissionSchema}};var renderNames=Object.keys(templates);var requiresWrite=name=>name==="local_render_prepare"||name==="local_render_start";function denied(){throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE")}async function selectedConnector(home,env){const account=requireAccount(await readAccount(await clientHome(env)));if(!account.workspaceId)denied();return desktopDeviceConnector(home,{origin:account.serverOrigin,tenantId:account.workspaceId,principalId:account.principalId})}var ProjectRenderTools=class _ProjectRenderTools{constructor(runtime,env,binding,deviceId,writable){this.runtime=runtime;this.env=env;this.binding=binding;this.deviceId=deviceId;this.writable=writable}runtime;env;binding;deviceId;writable;static async open(runtime,env){const c=await loadConnection(env,true);if(!c)denied();const projectId=await selectedProject(c,env);const scopes=c.scope.split(/\s+/);if(!scopes.includes("nvs:read"))denied();const status=await runtime.status(void 0,true);const authority=status.deviceAuthority;if(!authority||authority.origin!==new URL(c.resource).origin||authority.tenantId!==c.tenantId)denied();return new _ProjectRenderTools(runtime,env,{...c,projectId},authority.deviceId,scopes.includes("nvs:write"))}get names(){return this.writable?renderNames:renderNames.filter(name=>!requiresWrite(name))}schema(n){const t=templates[n];return{name:n,description:t.description,inputSchema:{...z.toJSONSchema(t.input,{io:"input"}),type:"object"},outputSchema:{...z.toJSONSchema(t.output,{io:"input"}),type:"object"},annotations:{readOnlyHint:n!=="local_render_start",destructiveHint:false,idempotentHint:true,openWorldHint:true}}}async call(n,raw,signal){const write=requiresWrite(n);if(write&&!this.writable)denied();const c=await renderConnection(this.env,signal,write);try{if(c.scope.resource!==this.binding.resource||c.scope.profile!==this.binding.profile||c.scope.projectId!==this.binding.projectId)denied();const s=await this.runtime.status(signal,true);if(s.deviceAuthority?.tenantId!==c.scope.tenantId||s.deviceAuthority.deviceId!==this.deviceId||s.deviceAuthority.origin!==new URL(c.scope.resource).origin)denied();const checked=templates[n].input.parse(raw);const productionId="productionId"in checked&&typeof checked.productionId==="string"?checked.productionId:n==="local_render_receipt"||n==="local_render_start"?PreparedDeviceRenderSchema.parse(raw).command.productionId:void 0;if(productionId)await assertRenderProject(c.studio,c.scope,productionId,{signal});if(n==="local_devices_list"){const input=templates.local_devices_list.input.parse(raw);return await c.studio.deviceRenders.list({...input,projectId:c.scope.projectId,deviceId:this.deviceId},{signal})}if(n==="local_render_get"){const view=await c.studio.deviceRenders.get(DeviceRenderReadSchema.parse(raw),{signal});if(view.projectId!==c.scope.projectId)denied();return view}if(n==="local_render_media_ticket"){const result=await c.studio.deviceRenders.mediaTicket(DeviceRenderDownloadSchema.parse(raw),{signal});if(result.ticket.object.projectId!==c.scope.projectId)denied();return result}if(n==="local_render_prepare"){const input=DeviceRenderIntentSchema.parse(raw);if(input.deviceId&&input.deviceId!==this.deviceId)denied();return await c.studio.deviceRenders.prepare({...input,deviceId:this.deviceId},{signal})}const prepared=PreparedDeviceRenderSchema.parse(raw);if(prepared.command.tenantId!==c.scope.tenantId||prepared.command.deviceExecution.deviceId!==this.deviceId)denied();const response=n==="local_render_receipt"?await c.studio.deviceRenders.receipt(prepared,{signal}):await c.studio.deviceRenders.start(prepared,{signal});const parsed=DeviceRenderAdmissionSchema.safeParse(response);if(!parsed.success)throw new NativeStudioSdkError("RESPONSE_INVALID","BLOCKED",n==="local_render_receipt"?"NO_WRITE":"UNKNOWN");return parsed.data}finally{await c.close().catch(()=>{})}}};async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const renderNames2=tools.renders?.names??[];const visible=[...tools.names??Object.keys(localTools).filter(name=>!name.startsWith("local_library_")),...renderNames2].sort(),pending=new Map;let initialized=false,closed=false;const frames=new StdioLines(65536);let finish;const ended=new Promise(resolve2=>{finish=resolve2});const send=message=>{if(closed)return;if(output.writableLength>512*1024){close(1);return}output.write(serializeMessage(message))};const error=(id,code,message)=>send({jsonrpc:"2.0",id,error:{code,message}});async function dispatch(r){if(pending.has(r.id)||pending.size>=8){error(r.id,-32e3,"Local request capacity unavailable");return}const abort=new AbortController;const timer=setTimeout(()=>abort.abort(),3e4);pending.set(r.id,abort);try{let result;if(r.method==="initialize"){if(initialized)throw Error();const v=r.params?.protocolVersion;if(typeof v!=="string")throw Error();const protocol=SUPPORTED_PROTOCOL_VERSIONS.includes(v)?v:LATEST_PROTOCOL_VERSION;initialized=true;result={protocolVersion:protocol,serverInfo:{name:"native-studio-local",version:identity.version},capabilities:{tools:{}},instructions:"Use local_navigate and local_capability_describe for scoped guidance. The standard tool list stays stable. Local tools inspect scoped mechanics. "+(tools.renders?"Use local_devices_list to inspect this device for render or processor kinds; use workspace_devices_list on the remote MCP for Workspace registrations without a Project, and list_devices for Project task candidates. Project render preparation and submission require write scope and target this device. Processor actions use their existing typed Project tools or nvs call. Owner CLI device-preflight reads setup prerequisites. ":"")+"Cloud owns native admission. Updates require a human CLI approval; MCP cannot stop or replace Runtime."}}else if(!initialized)throw Error();else if(r.method==="ping")result={};else if(r.method==="tools/list"){if(r.params?.cursor!==void 0)throw Error();result={tools:visible.map(n=>renderNames2.includes(n)?tools.renders.schema(n):tools.schema(n))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!visible.includes(name))throw Error();const render=renderNames2.includes(name)&&tools.renders;let data;try{data=render?await render.call(name,r.params?.arguments??{},abort.signal):await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z2.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=render?{semanticStatus:cause instanceof NativeStudioSdkError?cause.semanticStatus:code==="INVALID_INPUT"?code:"BLOCKED",error:{code:cause instanceof NativeStudioSdkError?cause.code:code,outcome:cause instanceof NativeStudioSdkError?cause.outcome:"NO_WRITE"},nextActions:[]}:LocalMcpFailureSchema.parse({semanticStatus:code==="INVALID_INPUT"?"INVALID_INPUT":"BLOCKED",error:{code,outcome:"NO_WRITE"},nextActions:[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:code==="FORBIDDEN"||code==="AUTHORIZATION_REQUIRED"?"AUTHORIZATION_REQUIRED":"UNAVAILABLE"}]});send({jsonrpc:"2.0",id:r.id,result:{isError:true,content:[{type:"text",text:JSON.stringify(failure)}],structuredContent:failure}});return}result={content:[{type:"text",text:JSON.stringify(data)}],structuredContent:data}}else{error(r.id,-32601,"Local method unavailable");return}send({jsonrpc:"2.0",id:r.id,result})}catch{error(r.id,-32602,"Local capability unavailable or authorization required")}finally{clearTimeout(timer);pending.delete(r.id)}}function onData(b){try{frames.push(b,line=>{const message=deserializeMessage(line.toString());if(isJSONRPCRequest(message))void dispatch(message);else if(isJSONRPCNotification(message)){if(message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")pending.get(id)?.abort()}}else throw Error();return!closed})}catch{close(1)}}function close(code=0){if(closed)return;closed=true;for(const abort of pending.values())abort.abort();input.off("data",onData);finish(code)}input.on("data",onData);input.once("end",()=>close(frames.incomplete?1:0));input.once("error",()=>close(1));output.once("error",()=>close(1));return{closed:ended,close:async()=>close()}}async function runLocalMcp(argv){try{const flags=new Map;const projectRenders=argv.includes("--with-project-renders");const library=argv.includes("--with-library");if(argv.filter(k=>k==="--with-library").length>1)throw Error();argv=argv.filter(k=>k!=="--with-library");if(argv.filter(k=>k==="--with-project-renders").length>1)throw Error();argv=argv.filter(k=>k!=="--with-project-renders");for(let i=0;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!k||!["--connector","--home"].includes(k)||!v||flags.has(k))throw Error();flags.set(k,v)}const home=resolve(flags.get("--home")??process.env.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client"));const env={...process.env,NATIVESTUDIO_CLIENT_HOME:home};const connector=flags.get("--connector")??await selectedConnector(home,env);const tools=await LocalMcpTools.open(resolve(connector),home,projectRenders?client=>ProjectRenderTools.open(client,env):void 0,library);const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("Local MCP needs a current scoped connector. Optional Project tools also need a connection to the same Project.\n");return 2}}export{runLocalMcp,serveLocalMcp};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{NativeStudioAccountClient,accountError,accountServerOrigin,clientHome,connectionStatus,defaultConnection,readAccount,requireAccount,saveAccount,withAccountLock}from"./chunk-TCZJLYSR.js";import"./chunk-FU3524Z6.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import{write}from"./chunk-KB2GVAN7.js";import"./chunk-A7EUJNCL.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";var aliases={find:"studio.start",overview:"studio.navigate",next:"studio.navigate",resume:"operation.get"};var auth=new Set(["--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"]);var fields={find:{"--query":"search","--project":"projectId","--limit":"limit","--next":"next","--attention":"attention"},overview:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},next:{"--production":"productionId","--project":"projectId","--goal":"goal","--limit":"actionLimit","--next":"actionNext"},resume:{"--production":"productionId","--operation":"operationId"},search:{"--query":"query","--project":"projectId","--group":"group","--family":"family","--limit":"limit","--next":"next"},describe:{"--tool":"tool","--project":"projectId","--reference":"schemaCursor"},groups:{"--project":"projectId"}};var NavigationCliCommands=new Set([...Object.keys(aliases),"capabilities"]);async function runNavigationCli(argv,stdin,call){const kind=argv[0]==="capabilities"?argv[1]?.startsWith("--")||!argv[1]?"groups":argv[1]:argv[0];const operation=argv[0]==="capabilities"?{groups:"studio.capability.groups",search:"studio.capability.search",describe:"studio.capability.describe"}[kind]:aliases[kind];const offset=argv[0]==="capabilities"&&argv[1]===kind?2:1;if(!operation||!fields[kind])throw Error("INVALID_INPUT");const forwarded=["call",operation],body={},seen=new Set;let input;for(let i=offset;i<argv.length;i+=2){const flag=argv[i],value=argv[i+1];if(!value||value.startsWith("--")||seen.has(flag))throw Error("INVALID_INPUT");seen.add(flag);if(auth.has(flag))forwarded.push(flag,value);else if(flag==="--input")input=value;else{const key=fields[kind][flag];if(!key)throw Error("INVALID_INPUT");body[key]=flag==="--limit"?Number(value):value}}if(input&&Object.keys(body).length)throw Error("INVALID_INPUT");forwarded.push("--input",input??"-");const generated=async function*(){yield Buffer.from(JSON.stringify(body))};return call(forwarded,input?stdin:generated())}import{randomBytes,randomUUID,createHash,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function accountSignals(timeout,run){const cancelled=new AbortController,signal=AbortSignal.any([AbortSignal.timeout(timeout),cancelled.signal]);const stop=()=>cancelled.abort();process.once("SIGINT",stop);process.once("SIGTERM",stop);try{return await run(signal)}finally{process.off("SIGINT",stop);process.off("SIGTERM",stop)}}async function runAccountLogin(argv,environment,hooks={}){const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--server","--browser","--timeout-ms"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_LOGIN_INPUT_INVALID");options.set(key,value)}const configured=options.get("--server")??environment.NATIVESTUDIO_STUDIO_ORIGIN;if(!configured)return{exitCode:2,output:{semanticStatus:"NEEDS_INPUT",error:{code:"ACCOUNT_SERVER_REQUIRED",outcome:"NO_WRITE"},nextSteps:["nvs login --server <Studio-origin> (no Project required)"]}};const origin=accountServerOrigin(configured),browser=options.get("--browser")??"auto",timeout=options.get("--timeout-ms")??"180000";if(!["auto","manual"].includes(browser)||!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)accountError("ACCOUNT_LOGIN_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(Number(timeout),async signal=>{if((await readAccount(root))?.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");const client=new NativeStudioAccountClient({serverOrigin:origin});await client.metadata(signal);const verifier=randomBytes(32).toString("base64url"),state=randomBytes(32).toString("base64url"),path="/account-callback/"+randomUUID();let finish,receiving=false,sent=false;const callback=new Promise(done=>{finish=done});const server=createServer({maxHeaderSize:8192,headersTimeout:5e3,requestTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address(),host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(receiving||req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||!req.url.startsWith(path+"?")||req.url.length>2048){res.writeHead(400).end("Invalid account callback.");return}const url=new URL(req.url,`http://${host}`),received=url.searchParams.get("state");const keys=[...url.searchParams.keys()];if(url.pathname!==path||new Set(keys).size!==keys.length||keys.some(k=>!["state","iss","code","error"].includes(k))||!received||Buffer.byteLength(received)!==Buffer.byteLength(state)||!timingSafeEqual(Buffer.from(received),Buffer.from(state))||url.searchParams.get("iss")!==origin||(url.searchParams.has("error")?url.searchParams.get("error")!=="access_denied"||url.searchParams.has("code"):!/^[A-Za-z0-9_-]{43}$/.test(url.searchParams.get("code")??""))){res.writeHead(400).end("Invalid account callback.");return}receiving=true;res.end("Account confirmation received. Return to NativeStudio CLI.");finish(url.searchParams.get("code"))});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});const attempt=join(root,"account-login-attempt.json");let attemptFile;try{await new Promise((done,fail)=>{server.once("error",fail);server.listen(0,"127.0.0.1",done)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirectUri=`http://127.0.0.1:${address.port}${path}`;const started=await client.start({redirectUri,state,codeChallenge:createHash("sha256").update(verifier).digest("base64url")},signal);const url=`${origin}/cli-authorize?requestId=${started.requestId}`;signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(url,signal);else{process.stderr.write(`CLI account login request: ${started.requestId}
|
|
2
|
+
`);if(browser==="manual")loginLink(url);else await openLoginBrowser(url,signal)}const code=await callback;if(!code)accountError(signal.aborted?signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED":"ACCOUNT_LOGIN_DENIED");const marker={version:1,serverOrigin:origin,requestId:started.requestId,state:"EXCHANGE_UNRESOLVED"};attemptFile=join(root,`account-login-attempt-${started.requestId}.json`);await write(attemptFile,JSON.stringify(marker),true);await write(attempt,JSON.stringify(marker));signal.throwIfAborted();sent=true;const session=await client.exchange({requestId:started.requestId,redirectUri,code,codeVerifier:verifier},signal);if(Date.parse(session.expiresAt)<=Date.now()||Date.parse(session.expiresAt)>Date.now()+36e5+3e4)accountError("ACCOUNT_SESSION_INVALID","UNKNOWN");await saveAccount(root,{version:1,epoch:randomUUID(),state:"ACTIVE",serverOrigin:origin,accessToken:session.accessToken,expiresAt:session.expiresAt,principalId:session.account.principalId,workspaceId:null,projectId:null});await write(attempt,JSON.stringify({...marker,state:"COMPLETED"}));await write(attemptFile,JSON.stringify({...marker,state:"COMPLETED"}));return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",serverOrigin:origin,expiresAt:session.expiresAt,account:session.account,nextSteps:["nvs workspaces","nvs workspace --id <workspace-id>","nvs projects"]}}}catch(error){if(sent){if(error instanceof NativeStudioSdkError&&error.outcome!=="UNKNOWN"){await write(attempt,JSON.stringify({version:1,state:"REJECTED"}));if(attemptFile)await write(attemptFile,JSON.stringify({version:1,state:"REJECTED"}));throw error}accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN")}if(error instanceof NativeStudioSdkError&&error.outcome==="UNKNOWN")accountError("ACCOUNT_LOGIN_OUTCOME_UNKNOWN","UNKNOWN");if(signal.aborted)accountError(signal.reason?.name==="TimeoutError"?"ACCOUNT_LOGIN_TIMED_OUT":"ACCOUNT_LOGIN_CANCELLED");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(done=>server.close(()=>done()))}}))}import{randomUUID as randomUUID2}from"node:crypto";import{z}from"zod";var AccountCommands=new Set(["whoami","workspaces","workspace","projects","project","logout"]);async function runAccountCommand(argv,environment){const command=argv[0],options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--id","--limit","--next"].includes(key)||!value||value.startsWith("--")||options.has(key))accountError("ACCOUNT_COMMAND_INPUT_INVALID");options.set(key,value)}if(["workspace","project"].includes(command??"")?options.size!==1||!options.has("--id"):command==="projects"?options.has("--id"):options.size!==0)accountError("ACCOUNT_COMMAND_INPUT_INVALID");const root=await clientHome(environment,true);return withAccountLock(root,()=>accountSignals(15e3,async signal=>{const stored=await readAccount(root);if(command==="logout"){if(!stored||stored.state==="SIGNED_OUT")return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:false}};const client2=new NativeStudioAccountClient({serverOrigin:stored.serverOrigin,accessToken:stored.accessToken});const pending={...stored,state:"REVOKE_PENDING",workspaceId:null,projectId:null};await saveAccount(root,pending);try{await client2.logout(signal);await saveAccount(root,{...pending,state:"SIGNED_OUT",accessToken:null})}catch{accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN")}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:false,changed:true,nextSteps:["nvs login --server <Studio-origin>"]}}}const account=requireAccount(stored),client=new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken});if(command==="whoami"||command==="workspaces"||command==="workspace"){const value2=await client.me(signal);if(value2.account.principalId!==account.principalId)accountError("ACCOUNT_IDENTITY_MISMATCH");if(command==="workspace"){const id=z.uuid().parse(options.get("--id"));if(!value2.account.tenants.some(t=>t.id===id))accountError("WORKSPACE_NOT_AUTHORIZED");await saveAccount(root,{...account,workspaceId:id,projectId:account.workspaceId===id?account.projectId:null,epoch:account.workspaceId===id?account.epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",workspaceId:id,nextSteps:["nvs projects"]}}}return{exitCode:0,output:{semanticStatus:"SUCCESS",authenticated:true,credentialPurpose:"CLI_ACCOUNT",verification:"LIVE_NATIVE_ACCOUNT",...command==="workspaces"?{workspaces:value2.account.tenants}:{account:value2.account,workspaceId:account.workspaceId,projectId:account.projectId,expiresAt:account.expiresAt},nextSteps:["nvs workspace --id <workspace-id>"]}}}if(!account.workspaceId)accountError("WORKSPACE_SELECTION_REQUIRED");if(command==="projects"){const limit=options.has("--limit")?z.coerce.number().int().min(1).max(100).parse(options.get("--limit")):void 0;const value2=await client.projects({tenantId:account.workspaceId,limit,next:options.get("--next")},signal);if(value2.items.some(p=>p.tenantId!==account.workspaceId))accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");return{exitCode:0,output:{semanticStatus:"SUCCESS",...value2,nextSteps:["nvs project --id <project-id>"]}}}if(command!=="project")accountError("ACCOUNT_COMMAND_INPUT_INVALID");const projectId=z.uuid().parse(options.get("--id")),value=await client.project({tenantId:account.workspaceId,projectId},signal);if(value.project.id!==projectId||value.project.tenantId!==account.workspaceId)accountError("ACCOUNT_RESPONSE_SCOPE_MISMATCH");if(value.project.lifecycle!=="ACTIVE")accountError("PROJECT_ARCHIVED");await saveAccount(root,{...account,projectId});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Use the existing workspace connection; run nvs connect if this workspace is not connected.","nvs status"]}}}))}var exits={SUCCESS:0,ACCEPTED:0,INVALID_INPUT:2,NOT_FOUND:3,BLOCKED:4,CAPABILITY_UNAVAILABLE:4,REVISION_CONFLICT:5};async function runRemoteCli(argv,environment=process.env,stdin=process.stdin){try{if(argv[0]==="connect")return await(await import("./project-connect-U2IHGC5W.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-U2IHGC5W.js");const result=await runProjectConnect(["connect",...argv.slice(1)],environment);return{...result,output:{...result.output,deprecated:{code:"PROJECT_AUTH_IS_CONNECT",replacement:"nvs connect --mcp-url <workspace-connection-url>",note:"This legacy spelling authorizes the requested MCP resource; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(argv[0]==="render")return await(await import("./render-main-A2AABFAG.js")).renderCommand(argv.slice(1),environment);if(argv[0]==="devices")return await(await import("./devices-main-WOILNAGY.js")).devicesCommand(argv.slice(1),environment,stdin);if(argv[0]==="import")return await(await import("./source-import-5N4KZMTC.js")).importSourceCommand(argv.slice(1),environment,stdin);if(AccountCommands.has(argv[0]??"")){const business=await(await import("./workspace-main-ZIZO4WRI.js")).workspaceCommand(argv,environment);return business??await runAccountCommand(argv,environment)}if(argv.length===1&&argv[0]==="status")return await connectionStatus(environment);if(NavigationCliCommands.has(argv[0]??""))return await runNavigationCli(argv,stdin,(args2,input2)=>runRemoteCli(args2,environment,input2));if(["auth-start","auth-complete"].includes(argv[0]??""))return await(await import("./oauth-WJ36KWAC.js")).runOAuthCommand(argv,stdin);if(!argv.length||argv.length===1&&["help","--help"].includes(argv[0]))return{exitCode:0,output:{product:"NativeStudio CLI",start:["nvs login --server <Studio-origin> \u2014 sign in/register your account in the browser; no project required.","nvs workspaces; nvs workspace --id <id>; nvs projects; nvs project --id <id>","nvs connect (authorizes the selected workspace once; supports its Projects and devices)","nvs status","nvs find --query <intent>"],navigation:["nvs capabilities","nvs overview --production <uuid>","nvs next --production <uuid>","nvs resume --production <uuid> --operation <op_original>"],agentConnection:{command:"nvs",args:["mcp"],note:"Uses the private saved connection; no token in Agent configuration."},commands:["login --server <Studio-origin> | whoami | logout \u2014 independent account session","workspaces | workspace --id <id> | projects [--limit <n>] [--next <cursor>] | project --id <id>","connect [--mcp-url <workspace-connection-url>] \u2014 authorize the workspace once for its Projects and devices","status","find --query <text> [--project <uuid>]","overview | next --production <uuid> [--goal <text>]","resume --production <uuid> --operation <op_original>","capabilities [groups | search --query <text> --group <group> | describe --tool <name>]","devices inventory [--device <uuid>] [--after <uuid>] [--limit <1..50>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read Workspace device registration and connection facts; no project required","devices list --kind preview|final|library|<processor-kind> [--project <uuid>] [--device <uuid>] [--mcp-url <workspace-url> --token-file <private-file>] \u2014 read candidates for this Project task; connection alone does not imply eligibility","devices enroll|revoke|receipt --input <json|-> \u2014 uses the saved tenant OAuth and original native command","render preview|final --production <uuid> --request <stable-uuid> [--project <uuid>] [--device <uuid>] [--validation-mode TENANT_TRUSTED_VALIDATOR] \u2014 tenant device only; saves original receipt","render status|download --kind preview|final --production <uuid> --render <uuid> [--project <uuid>] [--output <file>]","mcp \u2014 connect the Agent using the private saved connection","local help \u2014 installed Runtime, scoped local MCP, explicit exact-version updates"],advanced:["operations","mcp --profile <private-file> | --mcp-url <endpoint> --token-env <NAME>|--token-file <private-file>","call <operation> --input <file|-> --tenant <uuid> --token-env <NAME> --origin <https-origin>","call <operation> --input <file|-> --tenant <uuid> --token-file <private-file> --mcp-url <https-endpoint>","auth-start --profile <new-private-file> --mcp-url <resource> --callback <receiver-url>","auth-complete --profile <private-file> --input <callback-json-file|->","call <operation> --profile <private-file> --tenant <uuid> --input <file|->","import project|original --input <intent.json|-> --file <media> --tenant <uuid> --origin <https-origin> --token-file <private-file>"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations,sdkMcpTools,sdkCarrierDifferences,assertCarrierCoverage}=await import("./src-NIMTPR5W.js");if(argv.length===1&&argv[0]==="operations"){assertCarrierCoverage(sdkOperations,sdkCarrierDifferences);return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null,mcp:sdkMcpTools[name2],carrierDifference:Object.hasOwn(sdkCarrierDifferences,name2)?sdkCarrierDifferences[name2]:null}))}}}const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();if(name==="rough-cut.media-ticket"||name==="final-render.media-ticket")throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile","--transport"];for(let i=0;i<args.length;i+=2){const key2=args[i],value=args[i+1];if(!key2||!allowed.includes(key2)||!value||value.startsWith("--")||options.has(key2))throw Error();options.set(key2,value)}await defaultConnection(options,environment,true);if(!options.has("--input")||!options.has("--tenant")||(options.has("--profile")?options.has("--origin")||options.has("--mcp-url")||options.has("--token-file")||options.has("--token-env"):options.has("--origin")===options.has("--mcp-url")))throw Error();const key=name;const transport=options.get("--transport");if(transport&&!["http","mcp"].includes(transport))throw Error();if(!options.has("--profile")&&transport&&transport!==(options.has("--origin")?"http":"mcp"))throw Error();const input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-WJ36KWAC.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;const profileHttp=profile&&(transport==="http"||!transport&&sdkMcpTools[key]===null);if(!profileHttp&&(profile||options.has("--mcp-url"))){const{connectRemoteMcp}=await import("./mcp-6Q4ALHN6.js");const connection=await connectRemoteMcp(profile?.resource??options.get("--mcp-url"),authorization,tenantId);try{output=await connection.studio.call(key,input)}finally{await connection.close()}}else{const studio=new NativeStudioAgentClient({tenantId,baseUrl:profileHttp?await(await import("./http-profile-XCHTSJV4.js")).profileHttpOrigin(options.get("--profile"),profile.resource):options.get("--origin"),authorization:()=>authorization});output=await studio.call(key,input)}const status=output?.semanticStatus;return{exitCode:status?exits[status]??1:0,output}}catch(error){const e=error instanceof NativeStudioSdkError?error:null;const accountRecovery={ACCOUNT_LOGIN_OUTCOME_UNKNOWN:["Start a fresh nvs login --server <Studio-origin>; never replay the old exchange."],ACCOUNT_LOGOUT_OUTCOME_UNKNOWN:["Retry nvs logout explicitly; local account use remains locked."],ACCOUNT_LOGIN_REQUIRED:["nvs login --server <Studio-origin>"],ACCOUNT_SESSION_EXPIRED_OR_REVOKED:["nvs login --server <Studio-origin>"],WORKSPACE_SELECTION_REQUIRED:["nvs workspaces","nvs workspace --id <workspace-id>"],PROJECT_CONNECTION_ACCOUNT_MISMATCH:["nvs whoami","nvs workspaces","nvs project --id <project-id>","nvs connect --mcp-url <workspace-connection-url>"],ACCOUNT_PROJECT_SELECTION_REQUIRED:["nvs whoami","nvs workspace --id <workspace-id>","nvs project --id <project-id>"],PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED:["Authorization may exist. Inspect Web grants; select the intended account/project before creating a fresh connection."]};return{exitCode:e?exits[e.semanticStatus]??1:2,output:{semanticStatus:e?.semanticStatus??"INVALID_INPUT",error:{code:e?.code??"INVALID_INPUT",outcome:e?.outcome??"NO_WRITE"},...e&&accountRecovery[e.code]?{nextSteps:accountRecovery[e.code]}:{},...["PROJECT_CONNECTION_REQUIRED","OAUTH_OUTCOME_UNKNOWN"].includes(e?.code??"")?{nextSteps:["nvs connect --mcp-url <workspace-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{connectRemoteMcp}from"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import"./chunk-6NVIN2NI.js";export{connectRemoteMcp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,loadConnection,projectConnection,readAccount,saveConnection}from"./chunk-TCZJLYSR.js";import{profileAuthorization,runOAuthCommand}from"./chunk-DXJQWTLG.js";import{FileOAuthProvider}from"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-A7EUJNCL.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{randomUUID,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{join}from"node:path";async function runProjectConnect(argv,environment,hooks={}){if(argv[0]!=="connect")throw Error();const options=new Map;for(let i=1;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--mcp-url","--scope","--timeout-ms","--browser"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const root=await clientHome(environment,true),account=await readAccount(root);const explicit=options.get("--mcp-url");if(!explicit&&!account?.workspaceId)connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");const resource=projectConnection(explicit??new URL("/mcp/external/v1/tenants/"+account.workspaceId,account.serverOrigin).href);const scope=options.get("--scope")??(resource.projectId?"nvs:read":"nvs:read nvs:write");if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();const browser=options.get("--browser")??"auto";if(!["auto","manual"].includes(browser))throw Error();const timeout=options.get("--timeout-ms")??"180000";if(!/^\d+$/.test(timeout)||Number(timeout)<1e3||Number(timeout)>3e5)throw Error();const signal=AbortSignal.timeout(Number(timeout));const profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;if(account&&(account.state!=="ACTIVE"||account.workspaceId!==resource.tenantId||resource.projectId&&account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");if(!explicit){let saved=null;try{saved=await loadConnection(environment,true)}catch(error){if(!(error instanceof NativeStudioSdkError)||error.code!=="PROJECT_CONNECTION_ACCOUNT_MISMATCH")throw error}if(saved?.resource===resource.resource&&saved.scope===scope&&!saved.exchangeUnresolved){await profileAuthorization(saved.profile,signal);return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,resource:saved.resource,tenantId:saved.tenantId,projectId:saved.projectId,scope,reused:true}}}}let provider,receiving=false,redeeming=false;let finish;const callback=new Promise(resolve=>{finish=resolve});const server=createServer({maxHeaderSize:8192,requestTimeout:5e3,headersTimeout:5e3},(req,res)=>{res.setHeader("cache-control","no-store");res.setHeader("content-type","text/plain; charset=utf-8");res.setHeader("x-content-type-options","nosniff");const address=server.address();const host=address&&typeof address!=="string"?`127.0.0.1:${address.port}`:"";if(req.method!=="GET"||req.headers.host!==host||req.headers.origin||!req.url||req.url.length>4096||!req.url.startsWith(callbackPath+"?")||!provider||receiving){res.writeHead(400).end("Invalid authorization callback.");return}const url=new URL(req.url,`http://${host}`),state=url.searchParams.get("state");const expected=provider.data.state;const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(!state||Buffer.byteLength(state)!==Buffer.byteLength(expected)||!timingSafeEqual(Buffer.from(state),Buffer.from(expected))||url.searchParams.getAll("state").length!==1||url.pathname!==callbackPath||url.searchParams.getAll("iss").length!==1||url.searchParams.get("iss")!==issuer||(url.searchParams.has("error")?url.searchParams.has("code"):url.searchParams.getAll("code").length!==1||!url.searchParams.get("code"))){res.writeHead(400).end("Invalid authorization callback.");return}receiving=true;res.end("Authorization received. Return to NativeStudio CLI for the result.");finish(url.searchParams.has("error")?null:url.href)});server.maxConnections=8;const expired=()=>finish(null);signal.addEventListener("abort",expired,{once:true});try{await new Promise((resolve,reject)=>{server.once("error",reject);server.listen(0,"127.0.0.1",resolve)});const address=server.address();if(!address||typeof address==="string")throw Error();const redirect=`http://127.0.0.1:${address.port}${callbackPath}`;await runOAuthCommand(["auth-start","--profile",path,"--mcp-url",resource.resource,"--callback",redirect,"--scope",scope],empty(),signal);provider=await FileOAuthProvider.load(path);if(!provider.data.authorizationUrl)throw Error();signal.throwIfAborted();if(hooks.authorize)await hooks.authorize(provider.data.authorizationUrl,signal);else if(browser==="manual")loginLink(provider.data.authorizationUrl);else await openLoginBrowser(provider.data.authorizationUrl,signal);const received=await callback;if(!received)connectionError(signal.aborted?"LOGIN_TIMED_OUT":"LOGIN_DENIED");async function*input(){yield Buffer.from(JSON.stringify({callbackUrl:received}))}redeeming=true;await runOAuthCommand(["auth-complete","--profile",path,"--input","-"],input(),signal);const credentials=await saveConnection(root,profile,account?.epoch).catch(()=>{throw new NativeStudioSdkError("PROJECT_AUTHORIZED_CONNECTION_NOT_SELECTED","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")});return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,credentialPurpose:resource.projectId?"PROJECT_MCP":"TENANT_MCP",...resource,scope:credentials.scope,requestedScope:scope,nextSteps:["nvs status","nvs find --query <intent>","nvs mcp"]}}}catch(error){if(!redeeming&&signal.aborted)connectionError("LOGIN_TIMED_OUT");throw error}finally{signal.removeEventListener("abort",expired);server.closeAllConnections();await new Promise(resolve=>server.close(()=>resolve()))}}async function*empty(){}export{runProjectConnect};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{assertRenderProject}from"./chunk-DRHPICBU.js";import{callerRenderConnection}from"./chunk-TTFDNLQE.js";import"./chunk-XRYARPEL.js";import{clientHome}from"./chunk-TCZJLYSR.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import{directory,optional,sha256,write}from"./chunk-KB2GVAN7.js";import"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import{DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,PreparedDeviceRenderSchema}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";import{join,resolve}from"node:path";var receipt=z.strictObject({scope:z.string(),intent:DeviceRenderIntentSchema,prepared:PreparedDeviceRenderSchema});async function renderCommand(argv,env){const[kind,...args]=argv,flags=new Map;for(let i=0;i<args.length;i+=2){const k=args[i],v=args[i+1];if(!k||!v||v.startsWith("--")||flags.has(k)||!["--production","--project","--request","--device","--profile-id","--validation-mode","--kind","--render","--role","--output","--mcp-url","--token-file"].includes(k))throw Error();flags.set(k,v)}if(kind==="status"||kind==="download"){const allowed=new Set(["--kind","--project","--production","--render","--mcp-url","--token-file",...kind==="download"?["--role","--output"]:[]]);if(Array.from(flags.keys()).some(key=>!allowed.has(key)))throw Error();const input=DeviceRenderReadSchema.parse({kind:flags.get("--kind"),productionId:flags.get("--production"),renderId:flags.get("--render")});const conn2=await callerRenderConnection(env,flags,false);try{if(kind==="status"){const view=await conn2.studio.deviceRenders.get(input);if(view.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{exitCode:0,output:view}}const filename=flags.get("--output");if(!filename)throw Error();const request=DeviceRenderDownloadSchema.parse({...input,role:flags.get("--role")??"VIDEO"});const output=await conn2.studio.deviceRenders.download(request,void 0,conn2.scope.projectId);if(output.object.projectId!==conn2.scope.projectId)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");await write(resolve(filename),output.bytes,true);return{exitCode:0,output:{semanticStatus:"SUCCESS",renderId:output.renderId,representationId:output.representationId,byteSize:output.object.byteSize,checksumSha256:output.object.checksumSha256}}}finally{await conn2.close().catch(()=>{})}}if(["--kind","--render","--role","--output"].some(key=>flags.has(key)))throw Error();const intent=DeviceRenderIntentSchema.parse({kind,productionId:flags.get("--production"),idempotencyKey:z.uuid().parse(flags.get("--request")),...flags.has("--device")?{deviceId:flags.get("--device")}:{},...flags.has("--profile-id")?{profileId:flags.get("--profile-id")}:{},...flags.has("--validation-mode")?{validationMode:flags.get("--validation-mode")}:{}});const conn=await callerRenderConnection(env,flags);const binding=conn.scope.resource+"#"+sha256(conn.scope.profile)+(conn.scope.resource.endsWith("/projects/"+conn.scope.projectId)?"":"#"+conn.scope.projectId);try{await assertRenderProject(conn.studio,conn.scope,intent.productionId);const root=await directory(join(await clientHome(env,true),"renders"));const prefix=join(root,sha256(binding+"\n"+intent.idempotencyKey));const previous=await optional(prefix+".request.json");if(previous){const old=receipt.parse(previous);if(old.scope!==binding||JSON.stringify(old.intent)!==JSON.stringify(intent))throw new NativeStudioSdkError("REVISION_CONFLICT","REVISION_CONFLICT","NO_WRITE");const result=await optional(prefix+".result.json");if(result)return{exitCode:0,output:result};const failure=await optional(prefix+".failure.json");if(failure)return{exitCode:1,output:{semanticStatus:"BLOCKED",error:failure}};try{const recovered=await conn.studio.deviceRenders.receipt(old.prepared);await write(prefix+".result.json",JSON.stringify(recovered),true);return{exitCode:0,output:recovered}}catch(error){if(error instanceof NativeStudioSdkError&&error.code==="REVISION_CONFLICT")throw error}return{exitCode:1,output:{semanticStatus:"BLOCKED",error:{code:"OUTCOME_UNKNOWN",outcome:"UNKNOWN"},idempotencyKey:intent.idempotencyKey,productionId:intent.productionId,nextAction:"Repeat this command with the original request ID to observe its receipt."}}}const prepared=await conn.studio.deviceRenders.prepare(intent);await write(prefix+".request.json",JSON.stringify({scope:binding,intent,prepared}),true);let output;try{output=await conn.studio.deviceRenders.start(prepared)}catch(e){if(e instanceof NativeStudioSdkError&&e.outcome!=="UNKNOWN")await write(prefix+".failure.json",JSON.stringify({code:e.code,outcome:e.outcome,semanticStatus:e.semanticStatus}),true);throw e}try{await write(prefix+".result.json",JSON.stringify(output),true)}catch{throw new NativeStudioSdkError("OUTCOME_UNKNOWN","BLOCKED","UNKNOWN")}return{exitCode:0,output}}finally{await conn.close().catch(()=>{})}}export{renderCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{profileHttpOrigin}from"./chunk-RJ4QQF7E.js";import{defaultConnection,projectConnection}from"./chunk-TCZJLYSR.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import{readCredential,readInput}from"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import{NativeStudioAgentClient}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import"./chunk-6NVIN2NI.js";import{constants,open}from"node:fs/promises";async function sourceBytes(path,maxBytes){const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size<1||stat.size>maxBytes)throw Error();const bytes=Buffer.alloc(stat.size);let offset=0;while(offset<bytes.length){const{bytesRead}=await file.read(bytes,offset,bytes.length-offset,offset);if(!bytesRead)throw Error();offset+=bytesRead}if((await file.read(Buffer.alloc(1),0,1,offset)).bytesRead)throw Error();return bytes}finally{await file.close()}}async function importSourceCommand([kind,...args],env,stdin){if(kind!=="project"&&kind!=="original")throw Error();const flags=new Map;for(let index=0;index<args.length;index+=2){const name=args[index],value=args[index+1];if(!name||!value||value.startsWith("--")||flags.has(name)||!["--input","--file","--tenant","--origin","--mcp-url","--profile","--token-env","--token-file"].includes(name))throw Error();flags.set(name,value)}await defaultConnection(flags,env,true);const profile=flags.get("--profile");if(profile?["--origin","--mcp-url","--token-env","--token-file"].some(key=>flags.has(key)):flags.has("--origin")===flags.has("--mcp-url"))throw Error();const connected=profile?await profileAuthorization(profile):null;const resource=connected?.resource??flags.get("--mcp-url");const scope=resource?projectConnection(resource):null;if(scope&&flags.has("--tenant")&&flags.get("--tenant")!==scope.tenantId)throw Error();const input=flags.get("--input"),file=flags.get("--file"),tenantId=scope?.tenantId??flags.get("--tenant"),baseUrl=flags.get("--origin")??(connected&&profile?await profileHttpOrigin(profile,connected.resource):resource?new URL(resource).origin:void 0);if(!input||!file||!tenantId||!baseUrl)throw Error();const authorization=connected?.authorization??await readCredential(flags,env);const studio=new NativeStudioAgentClient({tenantId,baseUrl,authorization:()=>authorization});const intent=await readInput(input,stdin);const bytes=await sourceBytes(file,(kind==="project"?8:128)*1024*1024);const receipt=kind==="project"?await studio.directSources.importProjectSource(intent,bytes):await studio.directSources.importOriginal(intent,bytes);if(receipt.state==="SUBMITTED")return{exitCode:0,output:receipt};const output="registration"in receipt?{artifactId:receipt.registration.artifact.id,representationId:receipt.registration.primaryRepresentation.id}:{artifactId:receipt.original.artifactId,representationId:receipt.original.representationId,sourceId:receipt.original.sourceId,version:receipt.original.version};return{exitCode:0,output:{state:receipt.state,...output}}}export{importSourceCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CapabilityDescribeSchema,CapabilityGroupsSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,assertCarrierCoverage,navigationGroup,queryPages,sdkCarrierDifferences,sdkImageMediaTools,sdkMcpTools,sdkOperations,waitForOperation}from"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import{FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema}from"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-6NVIN2NI.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,DeviceDiscoveryInputSchema,DeviceRenderAdmissionSchema,DeviceRenderDownloadSchema,DeviceRenderIntentSchema,DeviceRenderReadSchema,FinalRenderViewSchema,LocalLibraryAdmissionSchema,LocalLibraryCommandQuerySchema,LocalLibraryCommandSchema,LocalLibraryCommandStatusSchema,LocalLibraryProjectionPageSchema,LocalLibraryProjectionQuerySchema,LocalLibraryReferenceSchema,NativeStudioAgentClient,NativeStudioDeviceRenders,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,PreparedDeviceRenderSchema,ProjectDeviceListSchema,RoughCutViewSchema,TenantRenderMediaTicketSchema,WorkspaceDeviceListInputSchema,WorkspaceDeviceListSchema,assertCarrierCoverage,navigationGroup,queryPages,sdkCarrierDifferences,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,waitForOperation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{StdioLines}from"./chunk-JFC6ZIGA.js";import{defaultConnection}from"./chunk-
|
|
1
|
+
import{StdioLines}from"./chunk-JFC6ZIGA.js";import{defaultConnection}from"./chunk-TCZJLYSR.js";import{FileOAuthProvider}from"./chunk-FU3524Z6.js";import{readCredential}from"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-A7EUJNCL.js";import"./chunk-VPYAXWXY.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import"./chunk-6NVIN2NI.js";async function stdioRelayConfig(argv,environment){const options=new Map;for(let i=0;i<argv.length;i+=2){const key=argv[i],value=argv[i+1];if(!key||!["--profile","--mcp-url","--token-env","--token-file","--timeout-ms","--discovery"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}await defaultConnection(options,environment,false);const discovery=options.get("--discovery");if(discovery!==void 0&&discovery!=="contextual-v1")throw Error();const timeout=options.get("--timeout-ms")??"30000";if(!/^\d+$/.test(timeout))throw Error();const timeoutMs=Number(timeout);if(!Number.isSafeInteger(timeoutMs)||timeoutMs<100||timeoutMs>3e5)throw Error();const profile=options.get("--profile");let endpoint,read;if(profile){if(options.has("--mcp-url")||options.has("--token-env")||options.has("--token-file"))throw Error();endpoint=secureEndpoint((await FileOAuthProvider.load(profile)).data.resource);read=async signal=>{const{profileAuthorization}=await import("./oauth-WJ36KWAC.js");const value=await profileAuthorization(profile,signal);if(secureEndpoint(value.resource).href!==endpoint.href)throw Error();return value.authorization}}else{if(!options.has("--mcp-url"))throw Error();endpoint=secureEndpoint(options.get("--mcp-url"));await readCredential(options,environment);read=()=>readCredential(options,environment)}let tail=Promise.resolve();return{endpoint,timeoutMs,...discovery?{discovery}:{},authorization(signal){const current=tail.then(()=>{signal.throwIfAborted();return read(signal)});tail=current.catch(()=>{});return current}}}import{isJSONRPCResultResponse}from"@modelcontextprotocol/client";var StdioContextualMenu=class{clear(){}request(request){return request}response(request,message){if(request.method!=="initialize"||!isJSONRPCResultResponse(message))return message;return{...message,result:{...message.result,instructions:["Navigation guidance: standard tools/list is stable. Use studio_start, studio_navigate and studio_capability_groups; describe returns a bounded public definition, not a tool-menu change. Follow native evidence and exact typed commands.",...typeof message.result.instructions==="string"?[message.result.instructions]:[]].join("\n")}}}};import{StreamableHTTPClientTransport,deserializeMessage,serializeMessage,isJSONRPCRequest,isJSONRPCNotification,isJSONRPCResultResponse as isJSONRPCResultResponse2,isJSONRPCErrorResponse}from"@modelcontextprotocol/client";var STDIO_RESPONSE_LIMIT=32*1024*1024;function stdioRelayFetch(config,shutdown){return async(input,init)=>{const target=new URL(input instanceof Request?input.url:String(input));if(target.href!==config.endpoint.href)throw Error();const signal=AbortSignal.any([shutdown,...init?.signal?[init.signal]:[],AbortSignal.timeout(config.timeoutMs)]);const authorization=await config.authorization(signal);signal.throwIfAborted();const headers=new Headers(init?.headers);headers.set("authorization",authorization);const response=await fetch(input,{...init,headers,signal,redirect:"error"});if(!response.body)return response;const declared=response.headers.get("content-length");if(declared&&(!/^\d+$/.test(declared)||Number(declared)>STDIO_RESPONSE_LIMIT)){await response.body.cancel();throw Error()}const reader=response.body.getReader();let size=0;const body=new ReadableStream({async pull(controller){try{const part=await reader.read();if(part.done){reader.releaseLock();controller.close();return}size+=part.value.byteLength;if(size>STDIO_RESPONSE_LIMIT){await reader.cancel();throw Error()}controller.enqueue(part.value)}catch(error){controller.error(error)}},async cancel(reason){await reader.cancel(reason);reader.releaseLock()}});return new Response(body,{status:response.status,statusText:response.statusText,headers:response.headers})}}var inputLimit=18*1024*1024;var concurrency=32;async function serveRemoteMcpStdio(config,input,output){const shutdown=new AbortController;const pending=new Map;const transport=new StreamableHTTPClientTransport(config.endpoint,{fetch:stdioRelayFetch(config,shutdown.signal),onInsufficientScope:"throw",reconnectionOptions:{maxRetries:0,maxReconnectionDelay:1,initialReconnectionDelay:1,reconnectionDelayGrowFactor:1}});const lines=new StdioLines(inputLimit);let queuedBytes=0,sends=0,stopped=false;let finish;const closed=new Promise(resolve=>{finish=resolve});const menu=config.discovery==="contextual-v1"?new StdioContextualMenu:void 0;function discard(id){const item=pending.get(id);if(item)clearTimeout(item.timer);pending.delete(id);return item}function write(message){if(stopped)return;const frame=serializeMessage(message);const bytes=Buffer.byteLength(frame);if(bytes>STDIO_RESPONSE_LIMIT||queuedBytes+bytes>STDIO_RESPONSE_LIMIT){void close(1);return}queuedBytes+=bytes;output.write(frame,error=>{queuedBytes-=bytes;if(error)void close(1)})}function fail(id,noWrite=false){const item=discard(id);item?.abort.abort();write({jsonrpc:"2.0",id,error:{code:-32603,message:"Remote MCP request unavailable",data:{semanticStatus:"INTERNAL_OPERATIONAL_FAILURE",outcome:noWrite?"NO_WRITE":"UNKNOWN"}}})}async function forward(message){if(isJSONRPCNotification(message)&&message.method==="notifications/cancelled"){const id=message.params?.requestId;if(typeof id==="string"||typeof id==="number")discard(id)?.abort.abort();if((transport.protocolVersion??"")>="2026-07-28")return}const request=isJSONRPCRequest(message)?message:null;if(request&&(pending.has(request.id)||pending.size>=concurrency||sends>=concurrency)){if(pending.has(request.id)){void close(2);return}fail(request.id,true);return}if(!request&&sends>=concurrency){void close(2);return}if(request){const version=request.method==="initialize"?request.params?.protocolVersion:request.params?._meta?.["io.modelcontextprotocol/protocolVersion"];if(typeof version==="string")transport.setProtocolVersion(version);const abort=new AbortController;const timer=setTimeout(()=>{if(pending.has(request.id))fail(request.id)},config.timeoutMs);timer.unref();pending.set(request.id,{abort,timer,request})}sends++;try{await transport.send(request&&menu?menu.request(request):message,request?{requestSignal:pending.get(request.id).abort.signal,onRequestStreamEnd:()=>{if(pending.has(request.id))fail(request.id)}}:{requestSignal:shutdown.signal})}catch{if(request&&pending.has(request.id))fail(request.id)}finally{sends--}}transport.onmessage=message=>{if(isJSONRPCResultResponse2(message)||isJSONRPCErrorResponse(message)){if(message.id===void 0)return;const item=discard(message.id);if(!item)return;if(item.request.method==="initialize"&&isJSONRPCResultResponse2(message)&&typeof message.result.protocolVersion==="string")transport.setProtocolVersion(message.result.protocolVersion);if(menu)message=menu.response(item.request,message)}if(isJSONRPCNotification(message)&&message.method==="notifications/tools/list_changed")menu?.clear();write(message)};transport.onerror=()=>{};function data(chunk){if(stopped)return;const bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);try{lines.push(bytes,line=>{void forward(deserializeMessage(new TextDecoder("utf-8",{fatal:true}).decode(line)));return!stopped})}catch{void close(2)}}function end(){void close(lines.incomplete?2:0)}function streamError(){void close(1)}async function close(code=0){if(stopped)return;stopped=true;shutdown.abort();for(const item of pending.values()){clearTimeout(item.timer);item.abort.abort()}pending.clear();menu?.clear();lines.clear();input.off("data",data).off("end",end).off("error",streamError);input.pause();output.off("error",streamError);try{await transport.close()}catch{code||=1}finish(code)}await transport.start();input.on("data",data).once("end",end).once("error",streamError);output.once("error",streamError);return{close,closed}}async function runMcpStdio(argv,environment){try{const config=await stdioRelayConfig(argv,environment);const handle=await serveRemoteMcpStdio(config,process.stdin,process.stdout);const stop=()=>{void handle.close()};process.once("SIGINT",stop);process.once("SIGTERM",stop);const code=await handle.closed;process.off("SIGINT",stop);process.off("SIGTERM",stop);if(code)process.stderr.write("NativeStudio MCP stdio connection failed.\n");return code}catch{process.stderr.write("NativeStudio MCP stdio configuration failed; run nvs status and nvs connect after account sign-in, or use explicit credentials.\n");return 2}}export{runMcpStdio};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{workspaceCommand,workspaceProject}from"./chunk-XRYARPEL.js";import"./chunk-TCZJLYSR.js";import"./chunk-DXJQWTLG.js";import"./chunk-FU3524Z6.js";import"./chunk-6LU6GJKW.js";import"./chunk-KB2GVAN7.js";import"./chunk-6SYHA2B4.js";import"./chunk-2UYKJ6YN.js";import"./chunk-RT5PFKYS.js";import"./chunk-A7EUJNCL.js";import"./chunk-FCHO4AVP.js";import"./chunk-VPYAXWXY.js";import"./chunk-PUNG4ND7.js";import"./chunk-6NVIN2NI.js";export{workspaceCommand,workspaceProject};
|