@nativestudio/cli 0.0.0-stage → 0.3.0-rc.1
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 +20 -0
- package/LICENSE +21 -0
- package/README.md +77 -2
- package/components/runtime.json +6 -0
- package/components/runtime.tgz +0 -0
- package/dist/BUNDLED_DEPENDENCIES.json +1 -0
- package/dist/_chunks/chunk-25EDDZQA.js +1 -0
- package/dist/_chunks/chunk-2UYKJ6YN.js +1 -0
- package/dist/_chunks/chunk-6NVIN2NI.js +1 -0
- package/dist/_chunks/chunk-E57YVMQ4.js +1 -0
- package/dist/_chunks/chunk-EAZKDCLD.js +1 -0
- package/dist/_chunks/chunk-G42IS5JF.js +1 -0
- package/dist/_chunks/chunk-GIEYSDCG.js +1 -0
- package/dist/_chunks/chunk-GJ7BZJLW.js +1 -0
- package/dist/_chunks/chunk-HLKERZIE.js +1 -0
- package/dist/_chunks/chunk-JFC6ZIGA.js +1 -0
- package/dist/_chunks/chunk-MSOMVWKN.js +1 -0
- package/dist/_chunks/chunk-PUNG4ND7.js +1 -0
- package/dist/_chunks/chunk-QC7RLTGU.js +1 -0
- package/dist/_chunks/chunk-RUMDDTON.js +1 -0
- package/dist/_chunks/chunk-U2UKGYGF.js +1 -0
- package/dist/_chunks/chunk-VDNNFVTZ.js +3 -0
- package/dist/_chunks/chunk-VPYAXWXY.js +1 -0
- package/dist/_chunks/files-TBJVDQWU.js +1 -0
- package/dist/_chunks/local-main-SOERK22D.js +1 -0
- package/dist/_chunks/local-mcp-JLPXXIDW.js +1 -0
- package/dist/_chunks/main-4SNF5EKE.js +2 -0
- package/dist/_chunks/mcp-EIMXNRH3.js +1 -0
- package/dist/_chunks/oauth-257CEUQH.js +1 -0
- package/dist/_chunks/project-connect-6MH2QG6G.js +1 -0
- package/dist/_chunks/src-7F6ZEU3U.js +1 -0
- package/dist/_chunks/stdio-main-JEADWO7U.js +1 -0
- package/dist/_types/cli/local/desktop-channel.d.ts +18 -0
- package/dist/_types/cli/local/desktop-contract.d.ts +208 -0
- package/dist/_types/cli/local/desktop-node.d.ts +1 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +32 -0
- package/dist/_types/cli/local/ledger.d.ts +309 -0
- package/dist/_types/cli/local/manager.d.ts +592 -0
- package/dist/_types/cli/local/mcp-tools.d.ts +419 -0
- package/dist/_types/cli/local/releases.d.ts +100 -0
- package/dist/_types/cli/local-management.d.ts +11 -0
- package/dist/_types/cli/local-navigation.d.ts +3 -0
- package/dist/_types/contracts/accepted-shot.d.ts +27 -0
- package/dist/_types/contracts/accepted-visual-source.d.ts +120 -0
- package/dist/_types/contracts/agent-execution-lifecycle.d.ts +749 -0
- package/dist/_types/contracts/agent-execution-oauth.d.ts +71 -0
- package/dist/_types/contracts/agent-execution-registration.d.ts +240 -0
- package/dist/_types/contracts/agent-execution-selection.d.ts +107 -0
- package/dist/_types/contracts/agent-host-execution.d.ts +706 -0
- package/dist/_types/contracts/agent-host-generic-transport.d.ts +12 -0
- package/dist/_types/contracts/agent-host.d.ts +226 -0
- package/dist/_types/contracts/artifact-discovery.d.ts +170 -0
- package/dist/_types/contracts/artifact.d.ts +188 -0
- package/dist/_types/contracts/audio.d.ts +331 -0
- package/dist/_types/contracts/brief.d.ts +178 -0
- package/dist/_types/contracts/caption-render.d.ts +20 -0
- package/dist/_types/contracts/caption-transcript.d.ts +102 -0
- package/dist/_types/contracts/captions.d.ts +420 -0
- package/dist/_types/contracts/clip-framing.d.ts +14 -0
- package/dist/_types/contracts/clip-transition.d.ts +6 -0
- package/dist/_types/contracts/composition-authoring-guide.d.ts +160 -0
- package/dist/_types/contracts/composition-authoring.d.ts +744 -0
- package/dist/_types/contracts/composition-finding-locality.d.ts +24 -0
- package/dist/_types/contracts/composition-frame-render.d.ts +226 -0
- package/dist/_types/contracts/composition-making.d.ts +390 -0
- package/dist/_types/contracts/composition-observation.d.ts +239 -0
- package/dist/_types/contracts/composition-render-base.d.ts +292 -0
- package/dist/_types/contracts/composition-render-observation.d.ts +278 -0
- package/dist/_types/contracts/composition-render.d.ts +406 -0
- package/dist/_types/contracts/composition-repair.d.ts +451 -0
- package/dist/_types/contracts/composition-source-review.d.ts +1042 -0
- package/dist/_types/contracts/consistency-profile.d.ts +845 -0
- package/dist/_types/contracts/continuity-evaluation.d.ts +48 -0
- package/dist/_types/contracts/delivery-completion.d.ts +210 -0
- package/dist/_types/contracts/delivery-manifest.d.ts +11776 -0
- package/dist/_types/contracts/delivery-operations.d.ts +5009 -0
- package/dist/_types/contracts/delivery-output-profile.d.ts +12 -0
- package/dist/_types/contracts/delivery-summary.d.ts +220 -0
- package/dist/_types/contracts/delivery-validation.d.ts +183 -0
- package/dist/_types/contracts/director-proposal.d.ts +1067 -0
- package/dist/_types/contracts/editor-intelligence.d.ts +5751 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +11863 -0
- package/dist/_types/contracts/external-agent-access.d.ts +95 -0
- package/dist/_types/contracts/final-ready.d.ts +301 -0
- package/dist/_types/contracts/final-render-profile.d.ts +59 -0
- package/dist/_types/contracts/final-render.d.ts +8181 -0
- package/dist/_types/contracts/foundation.d.ts +1 -0
- package/dist/_types/contracts/generation-contract.d.ts +268 -0
- package/dist/_types/contracts/generation-cost.d.ts +70 -0
- package/dist/_types/contracts/health.d.ts +6 -0
- package/dist/_types/contracts/human-identity.d.ts +149 -0
- package/dist/_types/contracts/hyperframe-profile.d.ts +5 -0
- package/dist/_types/contracts/ids.d.ts +41 -0
- package/dist/_types/contracts/index.d.ts +122 -0
- package/dist/_types/contracts/interface/common.d.ts +56 -0
- package/dist/_types/contracts/interface/execution-output.d.ts +99 -0
- package/dist/_types/contracts/interface/index.d.ts +7 -0
- package/dist/_types/contracts/interface/media-output.d.ts +62 -0
- package/dist/_types/contracts/interface/operation.d.ts +61 -0
- package/dist/_types/contracts/interface/output.d.ts +15 -0
- package/dist/_types/contracts/interface/production-snapshot.d.ts +832 -0
- package/dist/_types/contracts/interface/query.d.ts +315 -0
- package/dist/_types/contracts/keyframe-generation.d.ts +349 -0
- package/dist/_types/contracts/keyframe-reference.d.ts +31 -0
- package/dist/_types/contracts/keyframe-review.d.ts +753 -0
- package/dist/_types/contracts/lifecycle-event-projections.d.ts +191 -0
- package/dist/_types/contracts/lifecycle-events.d.ts +156 -0
- package/dist/_types/contracts/listening-evidence.d.ts +37 -0
- package/dist/_types/contracts/local-execution/agent-review.d.ts +560 -0
- package/dist/_types/contracts/local-execution/canonical.d.ts +2 -0
- package/dist/_types/contracts/local-execution/common.d.ts +48 -0
- package/dist/_types/contracts/local-execution/completion.d.ts +128 -0
- package/dist/_types/contracts/local-execution/device.d.ts +134 -0
- package/dist/_types/contracts/local-execution/index.d.ts +11 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1202 -0
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +319 -0
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +710 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +3663 -0
- package/dist/_types/contracts/local-execution/tool-selection.d.ts +15 -0
- package/dist/_types/contracts/local-execution/work.d.ts +3441 -0
- package/dist/_types/contracts/matrix-parameter-rule.d.ts +23 -0
- package/dist/_types/contracts/media-export.d.ts +23 -0
- package/dist/_types/contracts/media-observation.d.ts +1159 -0
- package/dist/_types/contracts/model-capability-matrix.d.ts +118 -0
- package/dist/_types/contracts/native-tool-authority-failure.d.ts +38 -0
- package/dist/_types/contracts/native-tool-authority.d.ts +110 -0
- package/dist/_types/contracts/native-tool-execution.d.ts +287 -0
- package/dist/_types/contracts/native-tool-gateway.d.ts +41 -0
- package/dist/_types/contracts/native-video-audio.d.ts +62 -0
- package/dist/_types/contracts/navigation-context.d.ts +253 -0
- package/dist/_types/contracts/navigation-groups.d.ts +51 -0
- package/dist/_types/contracts/navigation.d.ts +238 -0
- package/dist/_types/contracts/observation-profile.d.ts +99 -0
- package/dist/_types/contracts/planning-input.d.ts +177 -0
- package/dist/_types/contracts/principal.d.ts +26 -0
- package/dist/_types/contracts/production-creation.d.ts +66 -0
- package/dist/_types/contracts/production-termination.d.ts +51 -0
- package/dist/_types/contracts/production.d.ts +111 -0
- package/dist/_types/contracts/programmatic-composition.d.ts +762 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +7459 -0
- package/dist/_types/contracts/programmatic-video-review.d.ts +894 -0
- package/dist/_types/contracts/project-library.d.ts +173 -0
- package/dist/_types/contracts/project.d.ts +93 -0
- package/dist/_types/contracts/provider-catalog.d.ts +421 -0
- package/dist/_types/contracts/provider-models.d.ts +3380 -0
- package/dist/_types/contracts/provider.d.ts +142 -0
- package/dist/_types/contracts/reference-preview.d.ts +36 -0
- package/dist/_types/contracts/repair-lifecycle.d.ts +2896 -0
- package/dist/_types/contracts/repair-plan.d.ts +728 -0
- package/dist/_types/contracts/repair-strategy.d.ts +5751 -0
- package/dist/_types/contracts/review-intelligence-evidence.d.ts +136 -0
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +8705 -0
- package/dist/_types/contracts/review-intelligence.d.ts +11543 -0
- package/dist/_types/contracts/review1-repair-source.d.ts +452 -0
- package/dist/_types/contracts/review1-repair-strategy.d.ts +491 -0
- package/dist/_types/contracts/review1-repair.d.ts +36 -0
- package/dist/_types/contracts/rough-cut-manifest.d.ts +347 -0
- package/dist/_types/contracts/rough-cut-profile.d.ts +37 -0
- package/dist/_types/contracts/rough-cut-review.d.ts +12819 -0
- package/dist/_types/contracts/rough-cut.d.ts +5862 -0
- package/dist/_types/contracts/scene-shot-plan.d.ts +882 -0
- package/dist/_types/contracts/sdk-discovery.d.ts +66 -0
- package/dist/_types/contracts/shot-direction.d.ts +113 -0
- package/dist/_types/contracts/shot-preparation-basis.d.ts +356 -0
- package/dist/_types/contracts/shot-preparation.d.ts +2285 -0
- package/dist/_types/contracts/shot-sound-instruction.d.ts +58 -0
- package/dist/_types/contracts/sound-making-plan.d.ts +1585 -0
- package/dist/_types/contracts/source-sound-policy.d.ts +10 -0
- package/dist/_types/contracts/source-workspace.d.ts +62 -0
- package/dist/_types/contracts/speech.d.ts +424 -0
- package/dist/_types/contracts/story.d.ts +98 -0
- package/dist/_types/contracts/temporal-evidence-operation.d.ts +379 -0
- package/dist/_types/contracts/temporal-evidence-reference.d.ts +18 -0
- package/dist/_types/contracts/temporal-evidence.d.ts +248 -0
- package/dist/_types/contracts/tenant.d.ts +7 -0
- package/dist/_types/contracts/timeline-audio.d.ts +97 -0
- package/dist/_types/contracts/timeline-graphics.d.ts +80 -0
- package/dist/_types/contracts/timeline-manifest.d.ts +702 -0
- package/dist/_types/contracts/timeline-source-sound.d.ts +352 -0
- package/dist/_types/contracts/timeline-v2.d.ts +1263 -0
- package/dist/_types/contracts/timeline-version-reader.d.ts +2945 -0
- package/dist/_types/contracts/timeline-visual-layers.d.ts +1245 -0
- package/dist/_types/contracts/timeline.d.ts +4942 -0
- package/dist/_types/contracts/transcription.d.ts +80 -0
- package/dist/_types/contracts/video-generation.d.ts +643 -0
- package/dist/_types/contracts/video-review.d.ts +1871 -0
- package/dist/_types/contracts/visual-exploration.d.ts +1586 -0
- package/dist/_types/contracts/visual-layer-render.d.ts +2777 -0
- package/dist/_types/contracts/visual-layer.d.ts +112 -0
- package/dist/_types/contracts/visual-sequence.d.ts +121 -0
- package/dist/_types/contracts/writer-proposal.d.ts +268 -0
- package/dist/_types/sdk/errors.d.ts +9 -0
- package/dist/_types/sdk/local-runtime/device-client.d.ts +77 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +932 -0
- package/dist/entry.js +2 -0
- package/dist/local-management.d.ts +1 -0
- package/dist/local-management.js +1 -0
- package/dist/local-navigation.d.ts +1 -0
- package/dist/local-navigation.js +1 -0
- package/dist/native/Bootstrap.ps1 +90 -0
- package/dist/native/JobNative.cs +127 -0
- package/dist/native/JobRunner.cs +360 -0
- package/dist/native/NativeMain.cs +146 -0
- package/dist/native/PipeBridge.cs +260 -0
- package/dist/native/PrivateAccess.cs +152 -0
- package/package.json +33 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function secureEndpoint(endpoint){const url=new URL(endpoint);if(url.username||url.password||url.search||url.hash||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw Error();return url}var remoteResponse=(input,init)=>fetch(input,{...init,redirect:"error",signal:init?.signal?AbortSignal.any([init.signal,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)});var remoteFetch=async(input,init)=>{const response=await remoteResponse(input,init);if(!response.body)return response;const reader=response.body.getReader(),chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>32*1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}return new Response(Buffer.concat(chunks),{status:response.status,headers:response.headers})};export{secureEndpoint,remoteResponse,remoteFetch};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LocalExecutionListInputSchema,LocalMcpOutputSchemas,LocalWorkScopeSchema,NativeStudioLocalRuntimeClient,catalogue}from"./chunk-EAZKDCLD.js";import{fail,optional}from"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}from"zod";import{join}from"node:path";var localTools={local_navigate:{description:"Local execution entry. Discover Project-scoped Runtime progress, recovery and updates. Native writes remain with the cloud owner.",input:z.strictObject({intent:z.string().max(500).optional()})},local_capability_describe:{description:"Inspect the exact public schema for a local capability. Standard discovery stays stable; each call validates current Runtime authority.",input:z.strictObject({tool:z.enum(["local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"])})},local_runtime_status:{description:"Read current authorized local Runtime status. Does not start, stop or mutate native work.",input:z.strictObject({})},local_execution_list:{description:"List a bounded page of pending local execution identities in one authorized Project, then inspect an exact native Job.",input:LocalExecutionListInputSchema},local_execution_inspect:{description:"Inspect one exact native Job in the authorized Project. Native Job/Attempt identity remains authoritative.",input:LocalWorkScopeSchema},local_update_check:{description:"Read signed compatible release metadata only. No executable download, approval, installation or restart.",input:z.strictObject({})}};var LocalMcpTools=class _LocalMcpTools{constructor(client,home){this.client=client;this.home=home}client;home;static async open(connector,home){return new _LocalMcpTools(await NativeStudioLocalRuntimeClient.fromConnector(connector),home)}schema(name){return{name,description:localTools[name].description,inputSchema:z.toJSONSchema(localTools[name].input,{io:"input"}),outputSchema:z.toJSONSchema(LocalMcpOutputSchemas[name],{io:"input"}),annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:name==="local_update_check"}}}async call(name,raw,signal){return LocalMcpOutputSchemas[name].parse(await this.invoke(name,raw,signal))}async invoke(name,raw,signal){const input=localTools[name].input.parse(raw);if(name==="local_capability_describe")return{location:"LOCAL",tool:input.tool,schema:this.schema(input.tool)};if(name==="local_navigate"){let status;try{status=await this.client.status(signal)}catch{return{location:"LOCAL",state:"UNAVAILABLE",groups:[],nextActions:[{surface:"CLI",operation:"local.grant",availability:"BLOCKED",reason:"AUTHORIZATION_REQUIRED"}]}}return{location:"LOCAL",state:status.state,authorizedProjects:status.authorizedProjects,groups:[{id:"execution",label:"Local execution and recovery",tools:["local_runtime_status","local_execution_list","local_execution_inspect"]},{id:"versions",label:"Versions and updates",tools:["local_update_check"]}],nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"},availability:"AVAILABLE",reason:"READY"},...status.state==="RECOVERY_REQUIRED"?[{surface:"CLI",operation:"local.status",availability:"AVAILABLE",reason:"RECOVERY_REQUIRED"}]:[]]}}if(name==="local_runtime_status")return{...await this.client.status(signal),nextActions:[{tool:"local_capability_describe",arguments:{tool:"local_execution_list"}}]};if(name==="local_execution_list"){const page=await this.client.executions(LocalExecutionListInputSchema.parse(input),signal);return{...page,nextActions:page.items.map(item=>({tool:"local_execution_inspect",arguments:{tenantId:item.binding.tenantId,projectId:item.binding.projectId,productionId:item.binding.productionId,runtimeJobId:item.binding.runtimeJobId}}))}}if(name==="local_execution_inspect")return{location:"LOCAL",execution:await this.client.inspect(LocalWorkScopeSchema.parse(input),signal),nextActions:[]};if(name==="local_update_check"){const current=await this.client.status(signal);if(!current.authorizedProjects.length)throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const raw2=await optional(join(this.home,"configuration.json"));const config=z.object({catalogueUrl:z.string().url(),publicKeyFile:z.string()}).parse(raw2);const v=await catalogue(config,signal);return{location:"LOCAL",running:current.versions,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),nextActions:[{surface:"CLI",operation:"local.update.prepare",availability:"BLOCKED",reason:"USER_APPROVAL_REQUIRED"}]}}fail("CAPABILITY_UNAVAILABLE")}};export{localTools,LocalMcpTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CliAccountExchangeSchema,CliAccountIdentitySchema,CliAccountSessionSchema,CliAccountStartSchema,CliAccountStartedSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema}from"./chunk-GJ7BZJLW.js";import{FileOAuthProvider,withProfileLock}from"./chunk-MSOMVWKN.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{directory,optional,privateDirectory,write}from"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{homedir}from"node:os";import{isAbsolute,join}from"node:path";import{realpath}from"node:fs/promises";function connectionError(code){throw new NativeStudioSdkError(code,"INVALID_INPUT","NO_WRITE")}async function clientHome(environment,create=false){const path=environment.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client");if(!isAbsolute(path))connectionError("CLIENT_HOME_ABSOLUTE_REQUIRED");if(create)return directory(path);await privateDirectory(path);const root=await realpath(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))connectionError("CLIENT_HOME_PRIVATE_REQUIRED");return root}import{join as join2}from"node:path";import{z as z2}from"zod";import{z}from"zod";function accountServerOrigin(value){const url=new URL(value);if(url.pathname!=="/"||url.search||url.hash||url.username||url.password||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw new NativeStudioSdkError("ACCOUNT_SERVER_ORIGIN_REQUIRED","INVALID_INPUT","NO_WRITE");return url.origin}var NativeStudioAccountClient=class{constructor(options){this.options=options;this.serverOrigin=accountServerOrigin(options.serverOrigin);if(options.accessToken&&!/^nvsh_[A-Za-z0-9_-]{43}$/.test(options.accessToken))throw new NativeStudioSdkError("INVALID_ACCOUNT_CREDENTIAL","INVALID_INPUT","NO_WRITE")}options;serverOrigin;async request(action,schema,options={}){if(options.credential&&!this.options.accessToken)throw new NativeStudioSdkError("ACCOUNT_LOGIN_REQUIRED","INVALID_INPUT","NO_WRITE");const write2=options.body!==void 0;let response;try{response=await(this.options.fetch??fetch)(`${this.serverOrigin}/api/cli-account/${action}${options.query?"?"+options.query:""}`,{method:write2?"POST":"GET",cache:"no-store",redirect:"error",credentials:"omit",signal:AbortSignal.any([AbortSignal.timeout(15e3),...options.signal?[options.signal]:[]]),headers:{...write2?{"content-type":"application/json"}:{},...options.credential?{authorization:"Bearer "+this.options.accessToken}:{}},...write2?{body:JSON.stringify(options.body)}:{}})}catch{throw new NativeStudioSdkError("ACCOUNT_TRANSPORT_FAILED","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}if(!response.ok){await response.body?.cancel();throw new NativeStudioSdkError(response.status===401?"ACCOUNT_SESSION_EXPIRED_OR_REVOKED":"ACCOUNT_REQUEST_REJECTED","BLOCKED",write2&&response.status>=500?"UNKNOWN":"REJECTED",response.status)}try{if(!(response.headers.get("content-type")??"").startsWith("application/json"))throw Error();const reader=response.body?.getReader();if(!reader)throw Error();const chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(size);let offset=0;for(const part of chunks){bytes.set(part,offset);offset+=part.length}return schema.parse(JSON.parse(new TextDecoder().decode(bytes)))}catch{throw new NativeStudioSdkError("ACCOUNT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}}async metadata(signal){return this.request("metadata",z.strictObject({protocol:z.literal("NVS_CLI_ACCOUNT_V1"),serverOrigin:z.literal(this.serverOrigin)}),{signal})}start(input,signal){return this.request("start",CliAccountStartedSchema,{body:CliAccountStartSchema.parse(input),signal})}exchange(input,signal){return this.request("exchange",CliAccountSessionSchema,{body:CliAccountExchangeSchema.parse(input),signal})}me(signal){return this.request("me",CliAccountIdentitySchema,{credential:true,signal})}logout(signal){return this.request("logout",z.strictObject({changed:z.literal(true)}),{credential:true,body:{},signal})}async projects(input,signal){const value=z.strictObject({tenantId:z.uuid(),limit:z.number().int().min(1).max(100).optional(),next:z.string().min(1).max(8192).optional()}).parse(input);const result=await this.request("projects",ProjectLibraryPageSchema,{credential:true,signal,query:new URLSearchParams({tenantId:value.tenantId,...value.limit?{limit:String(value.limit)}:{},...value.next?{next:value.next}:{}})});if(result.items.some(p=>p.tenantId!==value.tenantId))throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}async project(input,signal){const value=z.strictObject({tenantId:z.uuid(),projectId:z.uuid()}).parse(input);const result=await this.request("project",ProjectWorkspaceSchema,{credential:true,signal,query:new URLSearchParams(value)});if(result.project.id!==value.projectId||result.project.tenantId!==value.tenantId)throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}};var AccountStateSchema=z2.strictObject({version:z2.literal(1),epoch:z2.uuid(),serverOrigin:z2.string().refine(v=>{try{return accountServerOrigin(v)===v}catch{return false}}),principalId:z2.uuid(),expiresAt:z2.iso.datetime(),workspaceId:z2.uuid().nullable(),projectId:z2.uuid().nullable(),state:z2.enum(["ACTIVE","REVOKE_PENDING","SIGNED_OUT"]),accessToken:z2.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/).nullable()}).refine(v=>v.state==="SIGNED_OUT"===(v.accessToken===null)&&(!v.projectId||Boolean(v.workspaceId)));function accountError(code,outcome="NO_WRITE"){throw new NativeStudioSdkError(code,outcome==="UNKNOWN"?"INTERNAL_OPERATIONAL_FAILURE":["ACCOUNT_LOGIN_INPUT_INVALID","ACCOUNT_COMMAND_INPUT_INVALID"].includes(code)?"INVALID_INPUT":"BLOCKED",outcome)}async function readAccount(root){const value=await optional(join2(root,"account.json"));if(value===null)return null;const parsed=AccountStateSchema.safeParse(value);if(!parsed.success)accountError("ACCOUNT_STATE_INVALID");return parsed.data}async function saveAccount(root,value){const account=AccountStateSchema.parse(value);const pointer=z2.object({version:z2.literal(1)}).passthrough().safeParse(await optional(join2(root,"connection.json")));if(pointer.success)await write(join2(root,"connection.json"),JSON.stringify({...pointer.data,version:2,accountEpoch:account.epoch}));await write(join2(root,"account.json"),JSON.stringify(account))}async function withAccountLock(root,action){try{return await withProfileLock(join2(root,"account.json"),action)}catch(error){if(error.code==="EEXIST")accountError("ACCOUNT_COMMAND_BUSY");throw error}}function requireAccount(value){if(!value)accountError("ACCOUNT_LOGIN_REQUIRED");if(value.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");if(value.state!=="ACTIVE"||Date.parse(value.expiresAt)<=Date.now())accountError("ACCOUNT_LOGIN_REQUIRED");return value}import{join as join3}from"node:path";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var projectPath=new RegExp(`^/mcp/external/v1/tenants/(${uuid})/projects/(${uuid})$`,"i");function projectConnection(resource){const url=secureEndpoint(resource),match=projectPath.exec(url.pathname);if(!match)connectionError("PROJECT_MCP_URL_REQUIRED");return{resource:url.href,tenantId:match[1],projectId:match[2]}}async function saveConnection(root,profile,expectedEpoch){return withAccountLock(root,()=>saveConnectionLocked(root,profile,expectedEpoch))}async function saveConnectionLocked(root,profile,expectedEpoch){if(!/^profile-[0-9a-f-]{36}\.json$/.test(profile))throw Error();const provider=await FileOAuthProvider.load(join3(root,profile));const scope=projectConnection(provider.data.resource);if(!provider.data.token?.access_token||provider.data.pendingExchange)throw Error();const account=await readAccount(root);if(account?.epoch!==expectedEpoch)connectionError("ACCOUNT_CHANGED_DURING_CONNECTION");if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==scope.tenantId||account.projectId!==scope.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");await write(join3(root,"connection.json"),JSON.stringify({version:account?2:1,profile,...scope,...account?{accountEpoch:account.epoch}:{}}));return{scope:provider.data.token.scope??provider.data.scope,expiresAt:provider.data.expiresAt}}async function loadConnection(environment,verifyAccount=false){let root;try{root=await clientHome(environment)}catch(e){if(e.code==="ENOENT")return null;throw e}const value=await optional(join3(root,"connection.json"));if(value===null)return null;if(value.version!==1&&value.version!==2||typeof value.profile!=="string"||!/^profile-[0-9a-f-]{36}\.json$/.test(value.profile)||typeof value.resource!=="string")connectionError("CONNECTION_INVALID");const scope=projectConnection(value.resource);if(scope.tenantId!==value.tenantId||scope.projectId!==value.projectId)connectionError("CONNECTION_SCOPE_MISMATCH");const account=await readAccount(root);if(value.version===2&&(!account||typeof value.accountEpoch!=="string"))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&(value.version!==2||account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||value.accountEpoch!==account.epoch||scope.tenantId!==account.workspaceId||scope.projectId!==account.projectId))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&verifyAccount){const identity=await new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken}).me();if(identity.account.principalId!==account.principalId||!identity.account.tenants.some(t=>t.id===scope.tenantId))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH")}const profile=join3(root,value.profile),provider=await FileOAuthProvider.load(profile);if(provider.data.resource!==scope.resource||!provider.data.token?.access_token)connectionError("CONNECTION_PROFILE_MISMATCH");return{...scope,profile,scope:provider.data.token.scope??provider.data.scope,requestedScope:provider.data.scope,expiresAt:provider.data.expiresAt,exchangeUnresolved:Boolean(provider.data.pendingExchange)}}var authentication=["--profile","--origin","--mcp-url","--token-env","--token-file"];async function defaultConnection(options,environment,tenant){if(authentication.some(key=>options.has(key)))return;const connection=await loadConnection(environment,true);if(!connection)connectionError("PROJECT_CONNECTION_REQUIRED");if(options.has("--tenant")&&options.get("--tenant")!==connection.tenantId)connectionError("CONNECTION_SCOPE_MISMATCH");options.set("--profile",connection.profile);if(tenant)options.set("--tenant",connection.tenantId)}async function connectionStatus(environment){const value=await loadConnection(environment);return{exitCode:0,output:value?{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",accountSessionVerified:false,verification:"LOCAL_METADATA_ONLY",resource:value.resource,tenantId:value.tenantId,projectId:value.projectId,scope:value.scope,requestedScope:value.requestedScope,expiresAt:value.expiresAt,credentialState:value.exchangeUnresolved?"EXCHANGE_UNRESOLVED":typeof value.expiresAt==="number"&&value.expiresAt>Date.now()+3e4?"CACHED":"REFRESH_REQUIRED",nextSteps:value.exchangeUnresolved?["Wait for the active authorization command. If it returned OAUTH_OUTCOME_UNKNOWN, run nvs connect --mcp-url <project-connection-url>."]:["nvs find --query <intent>","nvs capabilities","nvs mcp"]}:{semanticStatus:"NEEDS_INPUT",connected:false,credentialPurpose:"PROJECT_MCP",accountSessionVerified:false,nextSteps:["Sign in/register your account on Web or Electron, then select a workspace/project and open its Agent connection page.","nvs connect --mcp-url <project-connection-url>"]}}}export{connectionError,clientHome,accountServerOrigin,NativeStudioAccountClient,accountError,readAccount,saveAccount,withAccountLock,requireAccount,projectConnection,saveConnection,defaultConnection,connectionStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LocalDoctorReportSchema,LocalManagementInventorySchema,LocalRuntimeDescriptorSchema,LocalToolSelectionSchema,LocalUpdatePlanSchema,NativeStudioLocalRuntimeClient,asset,canonicalLocalJson,catalogue,select}from"./chunk-EAZKDCLD.js";import{directory,entries,fail,localSocketPath,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-GIEYSDCG.js";var requiredRuntimeFiles=["package.json","dist/entry.js","dist/supervisor.mjs","dist/parent-lifetime.mjs","dist/execution-identity.json"];var allowedRuntimeFiles=new Set([...requiredRuntimeFiles,"README.md","LICENSE","dist/THIRD_PARTY_NOTICES.md","dist/BUNDLED_DEPENDENCIES.json","dist/agent-supervisor.mjs",...["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"].map(name=>"dist/native/"+name)]);import{spawn}from"node:child_process";import{open}from"node:fs/promises";import{dirname,join,delimiter}from"node:path";var environment=()=>({...Object.fromEntries(["HOME","USER","LOGNAME","TMPDIR","CODEX_HOME","SystemRoot","SYSTEMROOT","USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP"].flatMap(k=>process.env[k]?[[k,process.env[k]]]:[])),PATH:dirname(process.execPath)+(process.platform==="win32"?"":delimiter+["/usr/bin","/bin"].join(delimiter)),LANG:"C",LC_ALL:"C",UV_THREADPOOL_SIZE:"2",NVS_INSTALL_OWNER:"MANAGED"});async function verifySlot(root,slot){if(requiredRuntimeFiles.some(name=>!Object.hasOwn(slot.files,name)))fail("SLOT_FILES_MISSING");for(const[name,hash]of Object.entries(slot.files)){if(!allowedRuntimeFiles.has(name))fail("SLOT_PATH_INVALID");if(sha256(await read(join(root,name),64*1024*1024))!==hash)fail("SLOT_INTEGRITY_INVALID")}}async function probe(root,expected){const bytes=await new Promise((resolve,reject)=>{const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--describe"],{env:environment(),stdio:["ignore","pipe","ignore"],shell:false});const parts=[];let size=0;const timer=setTimeout(()=>child.kill("SIGKILL"),1e4);child.stdout.on("data",b=>{size+=b.length;if(size>65536)child.kill("SIGKILL");else parts.push(b)});child.on("error",reject);child.on("close",code=>{clearTimeout(timer);if(code!==0||size>65536)reject(Error("Runtime descriptor unavailable"));else resolve(Buffer.concat(parts))})});const descriptor=LocalRuntimeDescriptorSchema.parse(JSON.parse(bytes.toString()));if(canonicalLocalJson(descriptor)!==canonicalLocalJson(expected))fail("RUNTIME_DESCRIPTOR_MISMATCH");return descriptor}async function ownerClient(stateDirectory){await directory(stateDirectory);return new NativeStudioLocalRuntimeClient({stateDirectory,authorization:async()=>"Bearer "+(await read(join(stateDirectory,"control-token"),128)).toString()})}async function runningInventory(client,root,slot){const inventory=await client.inventory(),status=await client.status();if(canonicalLocalJson(inventory.descriptor)!==canonicalLocalJson(slot.descriptor)||status.versions.find(v=>v.component==="RUNTIME")?.executablePath!==join(root,"dist/entry.js"))fail("RUNTIME_ALREADY_RUNNING");return inventory}async function launch(root,slot,stateDirectory,cloudConfig,toolsConfig){await verifySlot(root,slot);await probe(root,slot.descriptor);await directory(stateDirectory);const existing=await ownerClient(stateDirectory);try{return await runningInventory(existing,root,slot)}catch(e){if(e instanceof Error&&e.message.includes("RUNTIME_ALREADY_RUNNING"))throw e}const log=await open(join(stateDirectory,"runtime-process.log"),"a",384);const child=spawn(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"serve","--state-dir",stateDirectory,...cloudConfig?["--cloud-config",cloudConfig]:[],...toolsConfig?["--tools-config",toolsConfig]:[]],{env:environment(),detached:true,windowsHide:true,stdio:["ignore",log.fd,log.fd],shell:false});let spawnError=false;child.once("error",()=>{spawnError=true});child.unref();await log.close();const deadline=Date.now()+15e3;while(Date.now()<deadline){if(spawnError||child.exitCode!==null)fail("RUNTIME_START_FAILED");try{return await runningInventory(existing,root,slot)}catch{}await new Promise(r=>setTimeout(r,100))}child.kill("SIGTERM");fail("RUNTIME_START_UNCONFIRMED")}async function waitStopped(stateDirectory){const client=await ownerClient(stateDirectory),deadline=Date.now()+1e4;while(Date.now()<deadline){try{await client.inventory()}catch{const{lstat}=await import("node:fs/promises");try{if(process.platform!=="win32")await lstat(localSocketPath(stateDirectory))}catch(e){if(e.code==="ENOENT")return}const{createConnection}=await import("node:net");const closed=await new Promise(resolve=>{const s=createConnection(localSocketPath(stateDirectory));s.once("connect",()=>{s.destroy();resolve(false)});s.once("error",e=>resolve(["ECONNREFUSED","ENOENT"].includes(e.code??"")));s.setTimeout(300,()=>{s.destroy();resolve(false)})});if(closed)return}await new Promise(r=>setTimeout(r,100))}fail("RUNTIME_STOP_UNCONFIRMED")}async function socketAbsent(stateDirectory){const{createConnection}=await import("node:net");return new Promise(resolve=>{const socket=createConnection(localSocketPath(stateDirectory));socket.once("connect",()=>{socket.destroy();resolve(false)});socket.once("error",error=>resolve(["ECONNREFUSED","ENOENT"].includes(error.code??"")));socket.setTimeout(500,()=>{socket.destroy();resolve(false)})})}async function probeTools(root,stateDirectory,selection){const{execFile}=await import("node:child_process");const bytes=await new Promise((resolve,reject)=>execFile(process.execPath,["--max-old-space-size=256",join(root,"dist/entry.js"),"--qualify-tools","--state-dir",stateDirectory,"--tools-config",selection],{env:environment(),timeout:35e3,maxBuffer:65536},(error,stdout)=>error?reject(Error("Tool probe failed")):resolve(stdout)));const report=LocalDoctorReportSchema.parse(JSON.parse(bytes));if(report.availability!=="AVAILABLE")fail("TOOL_QUALIFICATION_FAILED");return report}function newerVersion(candidate,current){const parse=v=>{const core=v.split("+")[0],i=core.indexOf("-");return{parts:(i<0?core:core.slice(0,i)).split(".").map(BigInt),pre:i<0?null:core.slice(i+1).split(".")}};const a=parse(candidate),b=parse(current);for(let i=0;i<3;i++){if(a.parts[i]!==b.parts[i])return a.parts[i]>b.parts[i]}if(!a.pre||!b.pre)return!a.pre&&!!b.pre;for(let i=0;i<Math.max(a.pre.length,b.pre.length);i++){const x=a.pre[i],y=b.pre[i];if(x===y)continue;if(x===void 0||y===void 0)return y===void 0;const xn=/^\d+$/.test(x),yn=/^\d+$/.test(y);if(xn&&yn)return BigInt(x)>BigInt(y);if(xn!==yn)return!xn;return x>y}return false}async function identity(path,cloud){if(!path)return null;const raw=JSON.parse((await read(path,32768)).toString());const tools=LocalToolSelectionSchema.parse(cloud?raw.tools:raw);return tools.ffmpeg.digest+":"+tools.ffprobe.digest}async function effective(path,cloud){if(cloud){const raw=JSON.parse((await read(cloud,32768)).toString());if(LocalToolSelectionSchema.parse(raw.tools).mode==="INSTALLED")return identity(cloud,true)}return identity(path??cloud,!path)}async function assertPendingCompatible(raw,expected,previous,next,cloud){const i=LocalManagementInventorySchema.parse(raw);if(i.pendingRenderers.some(d=>d!==expected.rendererDigest))fail("NATIVE_RECOVERY_REQUIRED");if(i.pendingExecutions+i.pendingRequests===0)return;if(i.descriptor.profileDigest!==expected.profileDigest)fail("NATIVE_RECOVERY_REQUIRED");const before=await effective(previous,cloud);const after=await effective(next,cloud);if(!before||before!==after)fail("NATIVE_RECOVERY_REQUIRED")}import{randomUUID}from"node:crypto";import{join as join2,dirname as dirname2}from"node:path";import{z}from"zod";async function grant(manager,raw,output){const i=z.strictObject({projects:z.array(z.strictObject({tenantId:z.uuid(),projectId:z.uuid()})).min(1).max(100),expiresAt:z.iso.datetime({offset:true})}).parse(raw);const c=await manager.configuration(),client=await ownerClient(c.stateDirectory);await directory(dirname2(output));const connector=await client.call({operation:"session.issue",...i});await write(output,canonicalLocalJson(connector),true);await write(join2(manager.ledger.root,"grants",randomUUID()+".json"),canonicalLocalJson({...i,output}),true);return{granted:true,projects:i.projects,expiresAt:i.expiresAt}}async function reconnect(manager){const{entries:entries2}=await import("./files-TBJVDQWU.js"),c=await manager.configuration(),client=await ownerClient(c.stateDirectory);let renewed=0,blocked=0;for(const name of await entries2(join2(manager.ledger.root,"grants"))){if(!/^[0-9a-f-]{36}\.json$/.test(name))continue;try{const g=z.strictObject({projects:z.array(z.strictObject({tenantId:z.uuid(),projectId:z.uuid()})).max(100),expiresAt:z.iso.datetime({offset:true}),output:z.string().min(1)}).parse(await optional(join2(manager.ledger.root,"grants",name)));if(Date.parse(g.expiresAt)<=Date.now())continue;const connector=await client.call({operation:"session.issue",projects:g.projects,expiresAt:g.expiresAt});await write(g.output,canonicalLocalJson(connector));renewed++}catch{blocked++}}return{renewed,blocked}}import{randomUUID as randomUUID3}from"node:crypto";import{join as join6}from"node:path";import{z as z4}from"zod";import{z as z2}from"zod";import{join as join3}from"node:path";var slotSchema=z2.strictObject({id:z2.uuid(),descriptor:LocalRuntimeDescriptorSchema,toolsConfigPath:z2.string().nullable().default(null),files:z2.record(z2.string().min(1).max(100),z2.string().regex(/^[0-9a-f]{64}$/))});var transitionSchema=z2.strictObject({id:z2.uuid(),planId:z2.uuid(),fingerprint:z2.string().regex(/^[0-9a-f]{64}$/),phase:z2.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]),previous:slotSchema.nullable(),candidate:slotSchema.nullable(),backupPath:z2.string().nullable(),failedPhase:z2.enum(["STAGING","STAGED","DRAINING","ACTIVATING","VERIFYING","ROLLBACK_REQUIRED"]).nullable().default(null)});var installationSchema=z2.strictObject({revision:z2.int().nonnegative(),active:slotSchema.nullable(),transition:transitionSchema.nullable()});var recordSchema=z2.strictObject({previous:z2.string().nullable(),value:installationSchema,digest:z2.string().regex(/^[0-9a-f]{64}$/)});var InstallationLedger=class _InstallationLedger{constructor(root){this.root=root}root;static async open(path){const root=await directory(path);for(const name of["revisions","plans","slots","grants"])await directory(join3(root,name));return new _InstallationLedger(root)}async current(){const names=(await entries(join3(this.root,"revisions"))).filter(n=>/^\d{12}\.json$/.test(n)).sort();let previous=null,value={revision:0,active:null,transition:null};for(const[i,name]of names.entries()){const raw=JSON.parse((await read(join3(this.root,"revisions",name),262144,true)).toString());const r=recordSchema.parse(raw);const expected=sha256(canonicalLocalJson({previous:raw.previous,value:raw.value}));if(r.value.revision!==i+1||r.previous!==previous||r.digest!==expected)fail("INSTALLATION_HISTORY_INVALID");previous=r.digest;value=r.value}return{value,digest:previous}}async commit(expected,next){const current=await this.current();if(current.value.revision!==expected.revision)fail("REVISION_CONFLICT");const value=installationSchema.parse({...next,revision:expected.revision+1});const record={previous:current.digest,value,digest:sha256(canonicalLocalJson({previous:current.digest,value}))};try{await write(join3(this.root,"revisions",String(value.revision).padStart(12,"0")+".json"),canonicalLocalJson(record),true)}catch(e){if(e.code==="EEXIST")fail("REVISION_CONFLICT");throw e}return value}slotPath(slot){return join3(this.root,"slots",slot.id)}};import{randomUUID as randomUUID2}from"node:crypto";import{chmod as chmod2}from"node:fs/promises";import{join as join5}from"node:path";import{constants}from"node:fs";import{open as open2}from"node:fs/promises";import{z as z3}from"zod";var metadataSchema=z3.strictObject({protocol:z3.literal("NVS_PRODUCT_COMPONENT_V1"),version:z3.string().min(1).max(120),byteSize:z3.int().positive().max(64*1024*1024),sha512:z3.string().regex(/^[a-f0-9]{128}$/)});async function regularBytes(url,maximum){const file=await open2(url,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.size>maximum)fail("EMBEDDED_COMPONENT_INVALID");const bytes=Buffer.alloc(stat.size+1);let size=0;while(size<bytes.length){const result=await file.read(bytes,size,bytes.length-size,null);if(!result.bytesRead)break;size+=result.bytesRead}if(size!==stat.size)fail("EMBEDDED_COMPONENT_INVALID");return bytes.subarray(0,size)}finally{await file.close()}}async function verifiedEmbeddedAsset(base,release){try{const info=metadataSchema.parse(JSON.parse((await regularBytes(new URL("runtime.json",base),4096)).toString()));if(info.version!==release.descriptor.version)fail("EMBEDDED_RELEASE_MISMATCH");if(info.byteSize!==release.package.byteSize||info.sha512!==release.package.sha512)fail("EMBEDDED_RELEASE_MISMATCH");const bytes=await regularBytes(new URL("runtime.tgz",base),info.byteSize);if(bytes.length!==release.package.byteSize||sha512(bytes)!==release.package.sha512)fail("EMBEDDED_COMPONENT_INVALID");return bytes}catch(error){if(error instanceof Error&&error.message.includes("EMBEDDED_RELEASE_MISMATCH"))throw error;fail("EMBEDDED_COMPONENT_INVALID")}}async function embeddedAsset(release){if(false)return null;if(release.descriptor.version!=="0.3.0-rc.1")return null;if(false)fail("EMBEDDED_COMPONENT_INVALID");const base=new URL("./components/",import.meta.resolve("@nativestudio/cli/package.json"));return verifiedEmbeddedAsset(base,release)}import{gunzipSync}from"node:zlib";import{chmod}from"node:fs/promises";import{join as join4}from"node:path";async function unpack(bytes,root,expectedVersion){const data=gunzipSync(bytes,{maxOutputLength:64*1024*1024}),files=new Map;let offset=0;while(offset+512<=data.length){const header=data.subarray(offset,offset+512);if(header.every(b=>b===0))break;const text=(a,b)=>header.subarray(a,b).toString().replace(/\0.*$/s,"");const number=(a,b)=>{const v=text(a,b).trim();if(!/^[0-7]+$/.test(v))fail("PACKAGE_FORMAT_INVALID");return parseInt(v,8)};const sum=number(148,156);let actual=0;for(let i=0;i<512;i++)actual+=i>=148&&i<156?32:header[i];if(actual!==sum||!text(257,263).startsWith("ustar"))fail("PACKAGE_FORMAT_INVALID");const name=text(0,100),prefix=text(345,500),path=(prefix?prefix+"/":"")+name,size=number(124,136),kind=text(156,157);if(!Number.isSafeInteger(size)||size<0||offset+512+size>data.length)fail("PACKAGE_FORMAT_INVALID");if(kind==="5"){if(!/^package(?:\/dist(?:\/native)?)?\/?$/.test(path))fail("PACKAGE_PATH_INVALID")}else{if(kind!=="0"&&kind!=="")fail("PACKAGE_LINK_OR_METADATA_REFUSED");if(!path.startsWith("package/")||!allowedRuntimeFiles.has(path.slice(8))||files.has(path.slice(8)))fail("PACKAGE_PATH_INVALID");files.set(path.slice(8),data.subarray(offset+512,offset+512+size))}offset+=512+Math.ceil(size/512)*512}if(!requiredRuntimeFiles.every(p=>files.has(p)))fail("PACKAGE_FILES_MISSING");const manifest=JSON.parse(files.get("package.json").toString());const deps=manifest.dependencies;if(manifest.name!=="@nativestudio/local-runtime"||manifest.version!==expectedVersion||manifest.type!=="module"||Object.keys(deps??{}).length||Object.keys(manifest.optionalDependencies??{}).length||["preinstall","install","postinstall","prepare"].some(name=>Object.hasOwn(manifest.scripts??{},name))||!["dist/entry.js","./dist/entry.js"].includes(manifest.bin?.["nvs-runtime"]??"")||Object.keys(manifest.bin??{}).length!==1)fail("PACKAGE_IDENTITY_INVALID");const hashes={};await directory(join4(root,"dist"));if([...files.keys()].some(p=>p.startsWith("dist/native/")))await directory(join4(root,"dist/native"));for(const[path,contents]of files){await write(join4(root,path),contents,true);await chmod(join4(root,path),path.endsWith("entry.js")?320:256);hashes[path]=sha256(contents)}return hashes}async function stage(ledger,release,origin){const id=randomUUID2(),root=await directory(join5(ledger.root,"slots",id));const bytes=await embeddedAsset(release)??await asset(release.package,origin),files=await unpack(bytes,root,release.descriptor.version);const slot={id,files,descriptor:release.descriptor,toolsConfigPath:null};await probe(root,slot.descriptor);return slot}async function managedTools(release,origin,stateDirectory,selectionId){if(!release.tools)return null;const result={};for(const name of["ffmpeg","ffprobe"]){const a=release.tools[name],dir=await directory(join5(stateDirectory,"tools",a.sha256)),path2=join5(dir,name+(process.platform==="win32"?".exe":""));try{if(sha256(await read(path2,256*1024*1024))!==a.sha256)fail("TOOL_INTEGRITY_INVALID")}catch(e){if(e.code!=="ENOENT")throw e;const bytes=await asset(a,origin);if(sha256(bytes)!==a.sha256)fail("TOOL_INTEGRITY_INVALID");await write(path2,bytes,true);await chmod2(path2,320)}result[name]={path:path2,digest:a.sha256}}const selection={mode:"MANAGED",ffmpeg:result.ffmpeg,ffprobe:result.ffprobe};const path=join5(await directory(join5(stateDirectory,"tool-selections")),selectionId+".json");await write(path,JSON.stringify(selection));return path}async function selectedTools(release,origin,state,slotId,cloudConfig,previousSelection){if(cloudConfig){const raw=JSON.parse((await read(cloudConfig,32768)).toString());const selection=LocalToolSelectionSchema.parse(raw.tools);if(selection.mode==="INSTALLED"){const path=join5(await directory(join5(state,"tool-selections")),slotId+".json");await write(path,JSON.stringify(selection),true);return path}}return await managedTools(release,origin,state,slotId)??previousSelection}var configurationSchema=z4.strictObject({stateDirectory:z4.string().min(1).max(4096),catalogueUrl:z4.string().url(),publicKeyFile:z4.string().min(1).max(4096),cloudConfigFile:z4.string().nullable().default(null),notifications:z4.boolean().default(true),rejectedVersions:z4.array(LocalRuntimeDescriptorSchema.shape.version).max(64).default([])});var LocalInstallationManager=class _LocalInstallationManager{constructor(ledger){this.ledger=ledger}ledger;static async open(root){return new _LocalInstallationManager(await InstallationLedger.open(root))}async configure(raw,options={}){const c=configurationSchema.parse(raw);c.stateDirectory=await directory(c.stateDirectory);await write(join6(this.ledger.root,"configuration.json"),canonicalLocalJson(c),options.ifAbsent);return{configured:true}}async configuration(){const value=await optional(join6(this.ledger.root,"configuration.json"));if(!value)fail("CONFIGURATION_REQUIRED");return configurationSchema.parse(value)}async status(){const s=(await this.ledger.current()).value;let c;try{c=await this.configuration()}catch(error){if(error instanceof Error&&error.message.includes("CONFIGURATION_REQUIRED"))return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,running:null,phase:s.transition?.phase??"IDLE",nextActions:[{surface:"CLI",operation:"local.configure",availability:"AVAILABLE",reason:"INSTALL_REQUIRED"}]};throw error}let running=null;try{running=await(await ownerClient(c.stateDirectory)).status()}catch{}return{protocol:"NVS_LOCAL_INSTALLATION_STATUS_V1",revision:s.revision,activeVersion:s.active?.descriptor.version??null,entryPath:s.active?join6(this.ledger.slotPath(s.active),"dist/entry.js"):null,installOwner:"MANAGED",phase:s.transition?.phase??"IDLE",running,nextActions:[{surface:"CLI",operation:s.transition?"local.update.reconcile":s.active?"local.start":"local.install",availability:"AVAILABLE",reason:s.transition?"RECOVERY_REQUIRED":s.active?"READY":"INSTALL_REQUIRED"}]}}async reject(version){LocalRuntimeDescriptorSchema.shape.version.parse(version);const c=await this.configuration();await this.configure({...c,rejectedVersions:[...new Set([...c.rejectedVersions,version])]});return{rejected:true,version,selectedVersion:(await this.ledger.current()).value.active?.descriptor.version??null}}async check(){const c=await this.configuration(),v=await catalogue(c);return{installation:await this.status(),catalogueFingerprint:v.fingerprint,available:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch).map(r=>r.descriptor),notifications:c.notifications,rejectedVersions:c.rejectedVersions}}async prepare(version){const c=await this.configuration(),current=(await this.ledger.current()).value;if(current.transition)fail("ACTIVATION_IN_PROGRESS");const trusted=await catalogue(c),release=select(trusted.signed,version);let runtimeRevision=null;try{const inventory=await(await ownerClient(c.stateDirectory)).inventory();runtimeRevision=inventory.runtimeRevision;if(inventory.pendingRenderers.some(d=>d!==release.descriptor.rendererDigest))fail("NATIVE_RECOVERY_REQUIRED");await assertPendingCompatible(inventory,release.descriptor,current.active?.toolsConfigPath??null,current.active?.toolsConfigPath??null,c.cloudConfigFile)}catch(e){if(e instanceof Error&&e.message.includes("NATIVE_RECOVERY_REQUIRED"))throw e;if(!await socketAbsent(c.stateDirectory))fail("RUNTIME_STATUS_REQUIRED")}const body={protocol:"NVS_LOCAL_UPDATE_PLAN_V1",planId:randomUUID3(),installationRevision:current.revision,runtimeRevision,catalogueFingerprint:trusted.fingerprint,release,createdAt:new Date().toISOString(),expiresAt:new Date(Math.min(Date.now()+18e5,Date.parse(trusted.signed.catalogue.expiresAt))).toISOString()};const plan=LocalUpdatePlanSchema.parse({...body,fingerprint:sha256(canonicalLocalJson(body))});await write(join6(this.ledger.root,"plans",plan.planId+".json"),canonicalLocalJson(plan),true);return plan}async plan(id){if(!z4.uuid().safeParse(id).success)fail("PLAN_INVALID");const p=LocalUpdatePlanSchema.parse(JSON.parse((await read(join6(this.ledger.root,"plans",id+".json"))).toString()));const{fingerprint,...body}=p;if(sha256(canonicalLocalJson(body))!==fingerprint)fail("PLAN_CHANGED");return p}async transition(s,phase,patch={}){if(!s.transition)fail("TRANSITION_REQUIRED");return this.ledger.commit(s,{active:s.active,transition:{...s.transition,...patch,phase}})}async apply(id,approval){const plan=await this.plan(id),c=await this.configuration();if(approval!==plan.fingerprint)fail("USER_APPROVAL_REQUIRED");const trusted=await catalogue(c);if(Date.parse(plan.expiresAt)<=Date.now()||trusted.fingerprint!==plan.catalogueFingerprint||canonicalLocalJson(select(trusted.signed,plan.release.descriptor.version))!==canonicalLocalJson(plan.release))fail("PLAN_CHANGED");let s=(await this.ledger.current()).value;if(s.revision!==plan.installationRevision||s.transition)fail("REVISION_CONFLICT");if(plan.runtimeRevision!==null){const i=await(await ownerClient(c.stateDirectory)).inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>d!==plan.release.descriptor.rendererDigest))fail("REVISION_CONFLICT")}if(plan.runtimeRevision===null&&!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");s=await this.ledger.commit(s,{active:s.active,transition:{id:randomUUID3(),planId:id,fingerprint:approval,phase:"STAGING",previous:s.active,candidate:null,backupPath:null,failedPhase:null}});try{let candidate=await stage(this.ledger,plan.release,trusted.origin);const tools=await selectedTools(plan.release,trusted.origin,c.stateDirectory,candidate.id,c.cloudConfigFile,s.active?.toolsConfigPath??null);candidate={...candidate,toolsConfigPath:tools};if(tools)await probeTools(this.ledger.slotPath(candidate),c.stateDirectory,tools);s=await this.transition(s,"STAGED",{candidate});if(plan.runtimeRevision!==null){const client=await ownerClient(c.stateDirectory),i=await client.inventory();if(i.runtimeRevision!==plan.runtimeRevision||i.pendingRenderers.some(d=>d!==candidate.descriptor.rendererDigest))fail("REVISION_CONFLICT");await assertPendingCompatible(i,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile);s=await this.transition(s,"DRAINING");const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:plan.runtimeRevision});if(!result||typeof result!=="object"||!("backupPath"in result)||typeof result.backupPath!=="string")fail("JOURNAL_BACKUP_REQUIRED");await verifyBackup(result.backupPath,c.stateDirectory);s=await this.transition(s,"ACTIVATING",{backupPath:result.backupPath});await waitStopped(c.stateDirectory);await assertPendingCompatible("inventory"in result?result.inventory:null,candidate.descriptor,s.active?.toolsConfigPath??null,tools,c.cloudConfigFile)}else{if(!await socketAbsent(c.stateDirectory))fail("REVISION_CONFLICT");s=await this.transition(s,"ACTIVATING")}s=await this.ledger.commit(s,{active:candidate,transition:{...s.transition,phase:"VERIFYING"}});await this.startSlot(candidate,c);s=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{activated:true,revision:s.revision,version:candidate.descriptor.version}}catch(error){const actual=(await this.ledger.current()).value;if(actual.transition?.planId===id)await this.transition(actual,"ROLLBACK_REQUIRED",{failedPhase:actual.transition.phase});throw error}}async startSlot(slot,c){const chosen=c.cloudConfigFile?LocalToolSelectionSchema.parse(JSON.parse((await read(c.cloudConfigFile,32768)).toString()).tools):null;return launch(this.ledger.slotPath(slot),slot,c.stateDirectory,c.cloudConfigFile??void 0,chosen?.mode==="INSTALLED"?void 0:slot.toolsConfigPath??void 0)}async start(){const s=(await this.ledger.current()).value;if(s.transition)fail("ACTIVATION_IN_PROGRESS");if(!s.active)fail("INSTALL_REQUIRED");const c=await this.configuration(),inventory=await this.startSlot(s.active,c);const clients=await this.reconnect();let updateNotice={status:"DISABLED"};if(c.notifications){try{const v=await catalogue(c,AbortSignal.timeout(1500));updateNotice={status:"CHECKED",versions:v.signed.catalogue.releases.filter(r=>r.descriptor.platform.os===process.platform&&r.descriptor.platform.architecture===process.arch&&newerVersion(r.descriptor.version,s.active.descriptor.version)&&!c.rejectedVersions.includes(r.descriptor.version)).map(r=>r.descriptor.version)}}catch{updateNotice={status:"UNAVAILABLE"}}}return{...inventory,clients,updateNotice}}async stop(){const c=await this.configuration(),client=await ownerClient(c.stateDirectory),i=await client.inventory();const result=await client.call({operation:"runtime.stop",expectedRuntimeRevision:i.runtimeRevision});await waitStopped(c.stateDirectory);return result}async reconcile(id,approval){const s=(await this.ledger.current()).value,c=await this.configuration();if(!s.transition||s.transition.planId!==id||s.transition.fingerprint!==approval)fail("USER_APPROVAL_REQUIRED");if(s.active?.id===s.transition.previous?.id&&["STAGING","STAGED"].includes(s.transition.failedPhase??s.transition.phase)){const next2=await this.ledger.commit(s,{active:s.transition.previous,transition:null});return{rolledBack:true,revision:next2.revision,version:next2.active?.descriptor.version??null}}const candidate=s.transition.candidate;if(candidate){try{const i=await runningInventory(await ownerClient(c.stateDirectory),this.ledger.slotPath(candidate),candidate);if(canonicalLocalJson(i.descriptor)===canonicalLocalJson(candidate.descriptor)){await verifySlot(this.ledger.slotPath(candidate),candidate);const next2=await this.ledger.commit(s,{active:candidate,transition:null});await this.reconnect();return{recovered:true,revision:next2.revision,version:candidate.descriptor.version}}}catch{}}await waitStopped(c.stateDirectory);const previous=s.transition.previous;const next=await this.ledger.commit(s,{active:previous,transition:null});if(previous)await this.startSlot(previous,c);await this.reconnect();return{rolledBack:true,revision:next.revision,version:previous?.descriptor.version??null}}grant(raw,output){return grant(this,raw,output)}reconnect(){return reconnect(this)}};export{ownerClient,socketAbsent,LocalInstallationManager};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{spawn}from"node:child_process";import{join,isAbsolute}from"node:path";function loginLink(url){secureEndpoint(url.split("?")[0]);process.stderr.write(`Authorize NativeStudio in your browser:
|
|
2
|
+
${url}
|
|
3
|
+
`)}async function openLoginBrowser(url,signal){loginLink(url);let executable,args;if(process.platform==="darwin"){executable="/usr/bin/open";args=[url]}else if(process.platform==="linux"){executable="/usr/bin/xdg-open";args=[url]}else if(process.platform==="win32"&&process.env.SystemRoot&&isAbsolute(process.env.SystemRoot)){executable=join(process.env.SystemRoot,"System32","rundll32.exe");args=["url.dll,FileProtocolHandler",url]}else return;await new Promise(resolve=>{const child=spawn(executable,args,{shell:false,stdio:"ignore",windowsHide:true});const done=()=>{clearTimeout(timer);signal.removeEventListener("abort",stop);resolve()};const stop=()=>{child.kill();done()};const timer=setTimeout(stop,3e3);child.once("error",done);child.once("exit",done);signal.addEventListener("abort",stop,{once:true});if(signal.aborted)stop()})}export{loginLink,openLoginBrowser};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{z}from"zod";var TenantIdSchema=z.uuid().brand();var PrincipalIdSchema=z.uuid().brand();var ProjectIdSchema=z.uuid().brand();var ProductionIdSchema=z.uuid().brand();var ArtifactIdSchema=z.uuid().brand();var ArtifactRepresentationIdSchema=z.uuid().brand();var ArtifactRelationIdSchema=z.uuid().brand();var BriefIdSchema=z.uuid().brand();var BriefVersionIdSchema=z.uuid().brand();var StoryIdSchema=z.uuid().brand();var StoryVersionIdSchema=z.uuid().brand();var SceneShotPlanIdSchema=z.uuid().brand();var SceneShotPlanVersionIdSchema=z.uuid().brand();var SceneIdSchema=z.uuid().brand();var ShotIdSchema=z.uuid().brand();var ContinuityEdgeIdSchema=z.uuid().brand();var RuntimeJobIdSchema=z.uuid().brand();var OperationIdSchema=z.string().regex(/^op_[A-Za-z0-9_-]+$/).max(2048).brand();var RuntimeJobAttemptIdSchema=z.uuid().brand();var OutboxEventIdSchema=z.uuid().brand();import{z as z2}from"zod";var DeliveryOutputProfileSchema=z2.enum(["MP4_H264_1080P","MP4_H264_720P","MP4_H264_480P"]);var finalProfileIds={MP4_H264_1080P:"FINAL_H264_1080P_V1",MP4_H264_720P:"FINAL_H264_720P_V1",MP4_H264_480P:"FINAL_H264_480P_V1"};import{z as z3}from"zod";var InterfaceSemanticStatusSchema=z3.enum(["SUCCESS","ACCEPTED","NO_CHANGE","INVALID_INPUT","NOT_FOUND","REVISION_CONFLICT","STALE_BASIS","BLOCKED","WAITING_PROVIDER","WAITING_INPUT","RETRYING","CAPABILITY_UNAVAILABLE","PROVIDER_UNAVAILABLE","BUDGET_BLOCKED","CANCELLED","SUPERSEDED","INTERNAL_OPERATIONAL_FAILURE"]);var ActionAvailabilitySchema=z3.enum(["AVAILABLE","UNAVAILABLE"]);var NextActionSchema=z3.object({capability:z3.string().min(1).max(120),targetType:z3.string().min(1).max(80),targetId:z3.string().min(1).max(2048),availability:ActionAvailabilitySchema,reason:z3.string().min(1).max(1e3).nullable()});var ContinuationSchema=z3.string().min(1).max(8192);var QueryLimitSchema=z3.int().min(1).max(100).default(20);var QueryPageInfoSchema=z3.object({hasMore:z3.boolean(),next:ContinuationSchema.nullable()});var WorkSummarySchema=z3.object({total:z3.int().nonnegative(),pending:z3.int().nonnegative(),ready:z3.int().nonnegative(),running:z3.int().nonnegative(),waiting:z3.int().nonnegative(),succeeded:z3.int().nonnegative(),failed:z3.int().nonnegative(),cancelled:z3.int().nonnegative(),superseded:z3.int().nonnegative(),attempts:z3.int().nonnegative()});export{TenantIdSchema,PrincipalIdSchema,ProjectIdSchema,ProductionIdSchema,ArtifactIdSchema,ArtifactRepresentationIdSchema,ArtifactRelationIdSchema,BriefIdSchema,BriefVersionIdSchema,StoryIdSchema,StoryVersionIdSchema,SceneShotPlanIdSchema,SceneShotPlanVersionIdSchema,SceneIdSchema,ShotIdSchema,ContinuityEdgeIdSchema,OperationIdSchema,DeliveryOutputProfileSchema,finalProfileIds,InterfaceSemanticStatusSchema,NextActionSchema,ContinuationSchema,QueryLimitSchema,QueryPageInfoSchema,WorkSummarySchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LocalClientError,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write}from"./chunk-GIEYSDCG.js";export{LocalClientError,directory,entries,fail,optional,read,sha256,sha512,verifyBackup,write};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LocalInstallationManager,ownerClient}from"./chunk-U2UKGYGF.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{EnrollLocalDeviceSchema,GrantLocalDeviceSchema,LocalAgentGrantSchema,LocalDeviceTransportConfigurationSchema,LocalToolSelectionSchema,NativeStudioLocalDeviceClient,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,StartLocalPreviewSchema,canonicalLocalJson,localAgentNativeProposal,localAgentSnapshotFromContext}from"./chunk-EAZKDCLD.js";import{NativeStudioAgentClient}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{readCredential,readInput}from"./chunk-25EDDZQA.js";import{LocalClientError,directory,fail,read,write}from"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{generateKeyPairSync}from"node:crypto";import{dirname,join,sep}from"node:path";async function generateDeviceKey(output){await directory(dirname(output));const key=generateKeyPairSync("ec",{namedCurve:"prime256v1"});await write(output,JSON.stringify(key.privateKey.export({format:"jwk"})),true);return{publicKey:key.publicKey.export({format:"jwk"}),privateKeyFile:output}}async function connectDevice(manager,raw){const schema=LocalDeviceTransportConfigurationSchema.extend({tools:LocalToolSelectionSchema.optional()});const input=schema.parse(raw),c=await manager.configuration();await read(input.privateKeyFile,16384);let tools=input.tools;if(!tools){const selected=(await manager.ledger.current()).value.active?.toolsConfigPath;if(!selected)fail("MANAGED_TOOLS_REQUIRED");tools=LocalToolSelectionSchema.parse(JSON.parse((await read(selected,32768)).toString()))}if(tools.mode==="MANAGED"&&!tools.ffmpeg.path.startsWith(join(c.stateDirectory,"tools")+sep))fail("MANAGED_TOOLS_REQUIRED");const file=join(c.stateDirectory,"cloud-device.json");await write(file,canonicalLocalJson({...input,tools}));await manager.configure({...c,cloudConfigFile:file});return{connected:true,deviceId:input.deviceId,projects:input.projects,nextActions:[{surface:"CLI",operation:"local.stop",availability:"AVAILABLE",reason:"READY"},{surface:"CLI",operation:"local.start",availability:"AVAILABLE",reason:"READY"}]}}import{homedir as homedir2}from"node:os";import{join as join3,resolve as resolve2}from"node:path";import{homedir}from"node:os";import{join as join2,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));return{exitCode:0,output:{grant,fingerprint:createHash("sha256").update(canonicalLocalJson(grant)).digest("hex"),note:"Explicitly approves remote OpenAI inference/use for these Projects until expiry. Does not invoke a model."}}}if(flags.has("--evidence")&&!["IMAGE_PIXELS","METADATA_ONLY"].includes(need("--evidence")))throw Error();const manager=await LocalInstallationManager.open(resolve(flags.get("--home")??join2(homedir(),".nativestudio","client")));const client=await ownerClient((await manager.configuration()).stateDirectory);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":output=await client.prepareAgentReview(localAgentSnapshotFromContext(await readInput(need("--input"),stdin),flags.get("--evidence")==="IMAGE_PIXELS"));break;case"review-image-fetch":{const view=await client.inspectAgentReview(need("--id")),snapshot=view.plan.snapshot;if(!snapshot.image)throw Error();const studio=new NativeStudioAgentClient({baseUrl:need("--origin"),tenantId:snapshot.basis.scope.tenantId,authorization:()=>readCredential(flags,process.env)});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-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=localAgentNativeProposal(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?.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|grant|revoke-device|revoke-grant|preview --origin <cloud-origin> --token-file <member-token> --input <json>","connect --input <private-device-config>","version","install|update-prepare --version <exact>","update-check","update-reject --version <exact>","update-apply --plan <uuid> --approve <fingerprint>","update-reconcile --plan <uuid> --approve <fingerprint>","start","status","doctor","stop","grant --input <scopes-expiry-json> --output <new-private-connector>","mcp --connector <private-file>","agent-grant-plan|agent-probe|agent-grant|agent-revoke|review-prepare|review-image-fetch|review-start|review-inspect|review-proposal \u2014 see --input private JSON and exact --approve"],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);if(typeof input.tenantId!=="string")throw Error();const client=new NativeStudioLocalDeviceClient({baseUrl:required("--origin"),tenantId:input.tenantId,authorization:()=>readCredential(new Map([["--token-file",required("--token-file")]]),process.env)});const action=required("--action");const output2=action==="enroll"?await client.enroll(EnrollLocalDeviceSchema.parse(input)):action==="grant"?await client.grant(GrantLocalDeviceSchema.parse(input)):action==="revoke-device"?await client.revokeDevice(RevokeLocalDeviceSchema.parse(input)):action==="revoke-grant"?await client.revokeGrant(RevokeLocalDeviceGrantSchema.parse(input)):action==="preview"?await client.startPreview(StartLocalPreviewSchema.parse(input)):void 0;if(!output2)throw Error();return{exitCode:0,output:output2}}const manager=await LocalInstallationManager.open(resolve2(options.get("--home")??join3(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"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{LocalMcpTools,localTools}from"./chunk-QC7RLTGU.js";import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{LocalMcpFailureSchema}from"./chunk-EAZKDCLD.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import"./chunk-GIEYSDCG.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z}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";async function serveLocalMcp(tools,input,output){const identity=await localCliVersion();const visible=Object.keys(localTools).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. Cloud owns native business commands. 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=>tools.schema(n))}}else if(r.method==="tools/call"){const name=r.params?.name;if(typeof name!=="string"||!Object.hasOwn(localTools,name)||!visible.includes(name))throw Error();let data;try{data=await tools.call(name,r.params?.arguments??{},abort.signal)}catch(cause){const code=cause instanceof z.ZodError?"INVALID_INPUT":cause instanceof NativeStudioSdkError&&["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE"].includes(cause.code)?cause.code:"LOCAL_CAPABILITY_UNAVAILABLE";const failure=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;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 connector=flags.get("--connector");if(!connector)throw Error();const tools=await LocalMcpTools.open(resolve(connector),resolve(flags.get("--home")??join(homedir(),".nativestudio","client")));const service=await serveLocalMcp(tools,process.stdin,process.stdout);return await service.closed}catch{process.stderr.write("NativeStudio local MCP requires a private Project connector; use nvs local grant.\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-RUMDDTON.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import"./chunk-MSOMVWKN.js";import"./chunk-PUNG4ND7.js";import{readCredential,readInput}from"./chunk-25EDDZQA.js";import{write}from"./chunk-GIEYSDCG.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:null,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,epoch:randomUUID2()});return{exitCode:0,output:{semanticStatus:"SUCCESS",project:value.project,connectionPage:`${account.serverOrigin}/projects/${projectId}/settings`,nextSteps:["Open connectionPage, then explicitly authorize this Project using nvs connect.","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-6MH2QG6G.js")).runProjectConnect(argv,environment);if(argv[0]==="login"){if(argv.includes("--mcp-url")){const{runProjectConnect}=await import("./project-connect-6MH2QG6G.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 <project-connection-url>",note:"This legacy spelling authorizes one project; it does not establish a CLI account session."}}}}return await runAccountLogin(argv,environment)}if(AccountCommands.has(argv[0]??""))return 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-257CEUQH.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 --mcp-url <project-connection-url> (project authorization; read-only by default)","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 <project-connection-url> \u2014 project authorization after account sign-in","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>]","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|->"],note:"No automatic write retry. Transport abort does not cancel native Jobs."}};const{NativeStudioAgentClient,sdkOperations}=await import("./src-7F6ZEU3U.js");if(argv.length===1&&argv[0]==="operations")return{exitCode:0,output:{operations:Object.entries(sdkOperations).map(([name2,spec])=>({name:name2,readOnly:spec.readOnly??null,http:spec.request!==null}))}};const[command,name,...args]=argv;if(command!=="call"||!name||!Object.hasOwn(sdkOperations,name))throw Error();const options=new Map;const allowed=["--input","--tenant","--origin","--mcp-url","--token-env","--token-file","--profile"];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 input=await readInput(options.get("--input"),stdin);const profile=options.has("--profile")?await(await import("./oauth-257CEUQH.js")).profileAuthorization(options.get("--profile")):null;const authorization=profile?.authorization??await readCredential(options,environment);const tenantId=options.get("--tenant");let output;if(profile||options.has("--mcp-url")){const{connectRemoteMcp}=await import("./mcp-EIMXNRH3.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: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 <project-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 <project-connection-url>","nvs help"]}:{}}}}}export{runRemoteCli};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{remoteFetch,secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:remoteFetch});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client}),close:()=>client.close()}}catch{await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{profileAuthorization,runOAuthCommand}from"./chunk-G42IS5JF.js";import"./chunk-MSOMVWKN.js";import"./chunk-PUNG4ND7.js";import"./chunk-25EDDZQA.js";import"./chunk-GIEYSDCG.js";import"./chunk-6NVIN2NI.js";export{profileAuthorization,runOAuthCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loginLink,openLoginBrowser}from"./chunk-VDNNFVTZ.js";import{clientHome,connectionError,projectConnection,readAccount,saveConnection}from"./chunk-RUMDDTON.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{runOAuthCommand}from"./chunk-G42IS5JF.js";import{FileOAuthProvider}from"./chunk-MSOMVWKN.js";import"./chunk-PUNG4ND7.js";import"./chunk-25EDDZQA.js";import"./chunk-GIEYSDCG.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 resource=projectConnection(options.get("--mcp-url")??"");const scope=options.get("--scope")??"nvs:read";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 root=await clientHome(environment,true),profile=`profile-${randomUUID()}.json`;const path=join(root,profile),callbackPath=`/callback/${randomUUID()}`;const account=await readAccount(root);if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==resource.tenantId||account.projectId!==resource.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");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:"PROJECT_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{CapabilityDescribeSchema,CapabilityGroupsSchema,NativeStudioAgentClient,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,navigationGroup,queryPages,sdkImageMediaTools,sdkMcpTools,sdkOperations,waitForOperation}from"./chunk-E57YVMQ4.js";import"./chunk-GJ7BZJLW.js";import"./chunk-HLKERZIE.js";import"./chunk-VPYAXWXY.js";import{NativeStudioSdkError,sdkInputError}from"./chunk-6NVIN2NI.js";export{CapabilityDescribeSchema,CapabilityGroupsSchema,NativeStudioAgentClient,NativeStudioMcpClient,NativeStudioNavigationClient,NativeStudioNavigationFacade,NativeStudioRuntimeAuthorityClient,NativeStudioSdkError,NavigationGroupIdSchema,NavigationGroups,NavigationProfile,NavigationProfileKey,NavigationToolNames,navigationGroup,queryPages,sdkImageMediaTools,sdkInputError,sdkMcpTools,sdkOperations,waitForOperation};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{defaultConnection}from"./chunk-RUMDDTON.js";import{StdioLines}from"./chunk-JFC6ZIGA.js";import"./chunk-GJ7BZJLW.js";import"./chunk-VPYAXWXY.js";import{FileOAuthProvider}from"./chunk-MSOMVWKN.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{readCredential}from"./chunk-25EDDZQA.js";import"./chunk-GIEYSDCG.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-257CEUQH.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,18 @@
|
|
|
1
|
+
import type { LocalInstallationManager } from "./manager.js";
|
|
2
|
+
export declare function desktopRuntimeChannel(raw: unknown): {
|
|
3
|
+
value: {
|
|
4
|
+
catalogueUrl: string;
|
|
5
|
+
publicKey: string;
|
|
6
|
+
protocol: "NVS_DESKTOP_RUNTIME_CHANNEL_V1";
|
|
7
|
+
};
|
|
8
|
+
host: string;
|
|
9
|
+
fingerprint: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function desktopChannelInfo(manager: LocalInstallationManager, bundled?: unknown): Promise<{
|
|
12
|
+
protocol: "NVS_DESKTOP_CHANNEL_INFO_V1";
|
|
13
|
+
configured: boolean;
|
|
14
|
+
source: "UNAVAILABLE" | "EXISTING" | "BUNDLED";
|
|
15
|
+
host: string | null;
|
|
16
|
+
channelFingerprint: string | null;
|
|
17
|
+
}>;
|
|
18
|
+
export declare function configureDesktopChannel(manager: LocalInstallationManager, expectedFingerprint: string, bundled?: unknown): Promise<void>;
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const DesktopRuntimeChannelSchema: z.ZodObject<{
|
|
3
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_CHANNEL_V1">;
|
|
4
|
+
catalogueUrl: z.ZodString;
|
|
5
|
+
publicKey: z.ZodString;
|
|
6
|
+
}, z.core.$strict>;
|
|
7
|
+
export declare const DesktopOwnerRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
8
|
+
operation: z.ZodEnum<{
|
|
9
|
+
check: "check";
|
|
10
|
+
status: "status";
|
|
11
|
+
configuration: "configuration";
|
|
12
|
+
start: "start";
|
|
13
|
+
stop: "stop";
|
|
14
|
+
recovery: "recovery";
|
|
15
|
+
}>;
|
|
16
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
17
|
+
operation: z.ZodEnum<{
|
|
18
|
+
prepare: "prepare";
|
|
19
|
+
reject: "reject";
|
|
20
|
+
}>;
|
|
21
|
+
version: z.ZodString;
|
|
22
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
23
|
+
operation: z.ZodLiteral<"configure">;
|
|
24
|
+
channelFingerprint: z.ZodString;
|
|
25
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
26
|
+
operation: z.ZodEnum<{
|
|
27
|
+
apply: "apply";
|
|
28
|
+
recover: "recover";
|
|
29
|
+
}>;
|
|
30
|
+
planId: z.ZodUUID;
|
|
31
|
+
fingerprint: z.ZodString;
|
|
32
|
+
}, z.core.$strict>], "operation">;
|
|
33
|
+
export declare const DesktopRuntimeStatusSchema: z.ZodObject<{
|
|
34
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
35
|
+
state: z.ZodEnum<{
|
|
36
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
37
|
+
RUNNING: "RUNNING";
|
|
38
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
39
|
+
STOPPED: "STOPPED";
|
|
40
|
+
}>;
|
|
41
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
42
|
+
phase: z.ZodString;
|
|
43
|
+
}, z.core.$strict>;
|
|
44
|
+
export declare const DesktopUpdateCheckSchema: z.ZodObject<{
|
|
45
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_UPDATES_V1">;
|
|
46
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
47
|
+
versions: z.ZodArray<z.ZodObject<{
|
|
48
|
+
version: z.ZodString;
|
|
49
|
+
rejected: z.ZodBoolean;
|
|
50
|
+
}, z.core.$strict>>;
|
|
51
|
+
notifications: z.ZodBoolean;
|
|
52
|
+
}, z.core.$strict>;
|
|
53
|
+
export declare const DesktopOwnerPlanSchema: z.ZodObject<{
|
|
54
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
|
|
55
|
+
plan: z.ZodNullable<z.ZodObject<{
|
|
56
|
+
kind: z.ZodEnum<{
|
|
57
|
+
APPLY: "APPLY";
|
|
58
|
+
RECOVER: "RECOVER";
|
|
59
|
+
}>;
|
|
60
|
+
planId: z.ZodUUID;
|
|
61
|
+
fingerprint: z.ZodString;
|
|
62
|
+
version: z.ZodString;
|
|
63
|
+
previousVersion: z.ZodNullable<z.ZodString>;
|
|
64
|
+
expiresAt: z.ZodISODateTime;
|
|
65
|
+
phase: z.ZodString;
|
|
66
|
+
}, z.core.$strict>>;
|
|
67
|
+
}, z.core.$strict>;
|
|
68
|
+
export declare const DesktopChannelInfoSchema: z.ZodObject<{
|
|
69
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_CHANNEL_INFO_V1">;
|
|
70
|
+
configured: z.ZodBoolean;
|
|
71
|
+
source: z.ZodEnum<{
|
|
72
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
73
|
+
EXISTING: "EXISTING";
|
|
74
|
+
BUNDLED: "BUNDLED";
|
|
75
|
+
}>;
|
|
76
|
+
host: z.ZodNullable<z.ZodString>;
|
|
77
|
+
channelFingerprint: z.ZodNullable<z.ZodString>;
|
|
78
|
+
}, z.core.$strict>;
|
|
79
|
+
export declare const desktopOwnerResponses: {
|
|
80
|
+
readonly status: z.ZodObject<{
|
|
81
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
82
|
+
state: z.ZodEnum<{
|
|
83
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
84
|
+
RUNNING: "RUNNING";
|
|
85
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
86
|
+
STOPPED: "STOPPED";
|
|
87
|
+
}>;
|
|
88
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
89
|
+
phase: z.ZodString;
|
|
90
|
+
}, z.core.$strict>;
|
|
91
|
+
readonly start: z.ZodObject<{
|
|
92
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
93
|
+
state: z.ZodEnum<{
|
|
94
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
95
|
+
RUNNING: "RUNNING";
|
|
96
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
97
|
+
STOPPED: "STOPPED";
|
|
98
|
+
}>;
|
|
99
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
100
|
+
phase: z.ZodString;
|
|
101
|
+
}, z.core.$strict>;
|
|
102
|
+
readonly stop: z.ZodObject<{
|
|
103
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
104
|
+
state: z.ZodEnum<{
|
|
105
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
106
|
+
RUNNING: "RUNNING";
|
|
107
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
108
|
+
STOPPED: "STOPPED";
|
|
109
|
+
}>;
|
|
110
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
111
|
+
phase: z.ZodString;
|
|
112
|
+
}, z.core.$strict>;
|
|
113
|
+
readonly configure: z.ZodObject<{
|
|
114
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
115
|
+
state: z.ZodEnum<{
|
|
116
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
117
|
+
RUNNING: "RUNNING";
|
|
118
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
119
|
+
STOPPED: "STOPPED";
|
|
120
|
+
}>;
|
|
121
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
122
|
+
phase: z.ZodString;
|
|
123
|
+
}, z.core.$strict>;
|
|
124
|
+
readonly apply: z.ZodObject<{
|
|
125
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
126
|
+
state: z.ZodEnum<{
|
|
127
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
128
|
+
RUNNING: "RUNNING";
|
|
129
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
130
|
+
STOPPED: "STOPPED";
|
|
131
|
+
}>;
|
|
132
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
133
|
+
phase: z.ZodString;
|
|
134
|
+
}, z.core.$strict>;
|
|
135
|
+
readonly recover: z.ZodObject<{
|
|
136
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
137
|
+
state: z.ZodEnum<{
|
|
138
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
139
|
+
RUNNING: "RUNNING";
|
|
140
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
141
|
+
STOPPED: "STOPPED";
|
|
142
|
+
}>;
|
|
143
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
144
|
+
phase: z.ZodString;
|
|
145
|
+
}, z.core.$strict>;
|
|
146
|
+
readonly reject: z.ZodObject<{
|
|
147
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_STATUS_V1">;
|
|
148
|
+
state: z.ZodEnum<{
|
|
149
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
150
|
+
RUNNING: "RUNNING";
|
|
151
|
+
INSTALL_REQUIRED: "INSTALL_REQUIRED";
|
|
152
|
+
STOPPED: "STOPPED";
|
|
153
|
+
}>;
|
|
154
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
155
|
+
phase: z.ZodString;
|
|
156
|
+
}, z.core.$strict>;
|
|
157
|
+
readonly check: z.ZodObject<{
|
|
158
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_RUNTIME_UPDATES_V1">;
|
|
159
|
+
activeVersion: z.ZodNullable<z.ZodString>;
|
|
160
|
+
versions: z.ZodArray<z.ZodObject<{
|
|
161
|
+
version: z.ZodString;
|
|
162
|
+
rejected: z.ZodBoolean;
|
|
163
|
+
}, z.core.$strict>>;
|
|
164
|
+
notifications: z.ZodBoolean;
|
|
165
|
+
}, z.core.$strict>;
|
|
166
|
+
readonly configuration: z.ZodObject<{
|
|
167
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_CHANNEL_INFO_V1">;
|
|
168
|
+
configured: z.ZodBoolean;
|
|
169
|
+
source: z.ZodEnum<{
|
|
170
|
+
UNAVAILABLE: "UNAVAILABLE";
|
|
171
|
+
EXISTING: "EXISTING";
|
|
172
|
+
BUNDLED: "BUNDLED";
|
|
173
|
+
}>;
|
|
174
|
+
host: z.ZodNullable<z.ZodString>;
|
|
175
|
+
channelFingerprint: z.ZodNullable<z.ZodString>;
|
|
176
|
+
}, z.core.$strict>;
|
|
177
|
+
readonly prepare: z.ZodObject<{
|
|
178
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
|
|
179
|
+
plan: z.ZodNullable<z.ZodObject<{
|
|
180
|
+
kind: z.ZodEnum<{
|
|
181
|
+
APPLY: "APPLY";
|
|
182
|
+
RECOVER: "RECOVER";
|
|
183
|
+
}>;
|
|
184
|
+
planId: z.ZodUUID;
|
|
185
|
+
fingerprint: z.ZodString;
|
|
186
|
+
version: z.ZodString;
|
|
187
|
+
previousVersion: z.ZodNullable<z.ZodString>;
|
|
188
|
+
expiresAt: z.ZodISODateTime;
|
|
189
|
+
phase: z.ZodString;
|
|
190
|
+
}, z.core.$strict>>;
|
|
191
|
+
}, z.core.$strict>;
|
|
192
|
+
readonly recovery: z.ZodObject<{
|
|
193
|
+
protocol: z.ZodLiteral<"NVS_DESKTOP_OWNER_PLAN_V1">;
|
|
194
|
+
plan: z.ZodNullable<z.ZodObject<{
|
|
195
|
+
kind: z.ZodEnum<{
|
|
196
|
+
APPLY: "APPLY";
|
|
197
|
+
RECOVER: "RECOVER";
|
|
198
|
+
}>;
|
|
199
|
+
planId: z.ZodUUID;
|
|
200
|
+
fingerprint: z.ZodString;
|
|
201
|
+
version: z.ZodString;
|
|
202
|
+
previousVersion: z.ZodNullable<z.ZodString>;
|
|
203
|
+
expiresAt: z.ZodISODateTime;
|
|
204
|
+
phase: z.ZodString;
|
|
205
|
+
}, z.core.$strict>>;
|
|
206
|
+
}, z.core.$strict>;
|
|
207
|
+
};
|
|
208
|
+
export type DesktopOwnerPlan = z.infer<typeof DesktopOwnerPlanSchema>["plan"];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function materializeDesktopNode(home: string, source: string, expected: string, licenseDigest?: string): Promise<string>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Human installation owner adapter. It is never composed into scoped MCP. */
|
|
2
|
+
export declare function runDesktopOwnerRequest(home: string, raw: unknown, bundledChannel?: unknown): Promise<{
|
|
3
|
+
protocol: "NVS_DESKTOP_OWNER_PLAN_V1";
|
|
4
|
+
plan: {
|
|
5
|
+
kind: "APPLY" | "RECOVER";
|
|
6
|
+
planId: string;
|
|
7
|
+
fingerprint: string;
|
|
8
|
+
version: string;
|
|
9
|
+
previousVersion: string | null;
|
|
10
|
+
expiresAt: string;
|
|
11
|
+
phase: string;
|
|
12
|
+
} | null;
|
|
13
|
+
} | {
|
|
14
|
+
protocol: "NVS_DESKTOP_CHANNEL_INFO_V1";
|
|
15
|
+
configured: boolean;
|
|
16
|
+
source: "UNAVAILABLE" | "EXISTING" | "BUNDLED";
|
|
17
|
+
host: string | null;
|
|
18
|
+
channelFingerprint: string | null;
|
|
19
|
+
} | {
|
|
20
|
+
protocol: "NVS_DESKTOP_RUNTIME_STATUS_V1";
|
|
21
|
+
state: "UNAVAILABLE" | "RUNNING" | "INSTALL_REQUIRED" | "STOPPED";
|
|
22
|
+
activeVersion: string | null;
|
|
23
|
+
phase: string;
|
|
24
|
+
} | {
|
|
25
|
+
protocol: "NVS_DESKTOP_RUNTIME_UPDATES_V1";
|
|
26
|
+
activeVersion: string | null;
|
|
27
|
+
versions: {
|
|
28
|
+
version: string;
|
|
29
|
+
rejected: boolean;
|
|
30
|
+
}[];
|
|
31
|
+
notifications: boolean;
|
|
32
|
+
}>;
|